Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compute a function in a list?

Tags:

python

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)
like image 666
Maxwell's Daemon Avatar asked Feb 06 '26 10:02

Maxwell's Daemon


1 Answers

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().

like image 58
NPE Avatar answered Feb 08 '26 22:02

NPE