I'm reading "A Primer on Scientific Programming with Python" book and I'm stuck on exercise 2.26. It is said to write a function maxmin(f, a, b, n=1000) that returns the maximum and minimum values of a mathematical function f(x) (evaluated at n points) in the interval between a and b.
The maxmin function can compute a set of n coordinates between a and b stored in a list x, then compute f at the points in x and store the values in another list y. The Python functions max(y) and min(y) return the maximum and minimum values in the list y, respectively.
As a test, it is said that
from math import cos, pi
print maxmin(cos, -pi/2, 2*pi)
should write out(1.0, -1.0)
This is what I tried, but it doesn't return anything!
from math import cos, pi
def maxmin(f, a, b, n=1000):
x = [f(i) for i in range(a, b, n)]
#print x
maximum = max(x)
minimum = min(x)
return maximum, minimum
print maxmin(cos, -pi/2, 2*pi)
Your code is using range() incorrectly. The function does not support floating-point arguments and the last argument isn't what you think it is.
If I remember rightly, the book you are following is based around NumPy. If that's the case, you can simply replace range() with numpy.linspace().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With