python - What is the solution/workflow to make use of my functions with Numpy and Matplotlib on the example of cash amount calculations on perpetuity? -
i make matplotlib plot of the amount of cash agglomerated perpetuity against time. use numpy the generation of x axis data.
problem: there seems problem when using functions defined below numpy arrays. suspect has fact functions not vectorized, , there difference between iterative , recursive function definitions. unfortunatly, numpy.vectorize not solve issue.
questions:
how bring example work? , best workflow deal such plotting objectives? whey recursive , iterative functions give different errors? why numpy.vectorize
not here?
my code looks this:
agglomerated interest:
def a(a,r,t,n): """calculates combined interest initial amount a, interest rate r, times of compounding per year n , time t.""" return * pow((1 + r/n),(n*t))
perpetuity, recursive:
def p_rec(a,r,t,n): """returns total amount has accumulated perpetuity initial amount a, interest rate r , time t.""" result = 0 if t == 0: result else: result = result + a(a,r,t,n) + p_rec(a,r,(t-1),n) return result
perpetuity, iterative:
def p_it(a,r,t,n): """iterative implemenation of p_rec.""" result = 0 in range(1,t+1): result = result + a(a,r,i,n) return result
vectorized functions creatred numpy.vectorize:
from numpy import vectorize p_rec_v = vectorize (p_rec) p_it_v = vectorize (p_it)
plotting data:
%matplotlib inline import numpy np import matplotlib.pyplot plt import math plt.plot(x, a(10,0.16,x,1), 'ro', x, p_it(10,0.16,x,1), 'g^', x, p_rec(10,0.16,x,1), 'r--') plt.axis([0, 10, 0, 30]) plt.show()
errors:
the iterative , recursive version of p function give different errors. not understand why case.
p_rec gives "valueerror: truth value of array more 1 element ambiguous. use a.any() or a.all()"
p_it gives: "typeerror: integer arrays 1 element can converted index"
vectorized p_it: typeerror: 'numpy.float64' object cannot interpreted integer
vectorized p_rec: generates repetitive traceback due recursive nature of function.
Comments
Post a Comment