2

I have python scipy optimize with function f(x) = sin(x) and I want to plot the result. how can I do that? I am already have try with this code. but I get this error: TypeError: only length-1 arrays can be converted to Python scalars

here it is my code :

'''Import Python math library'''
import math
import matplotlib.pyplot as plt
'''try and except ImportError handler will be printing message if you haven't install required python library'''
try:
    import scipy.optimize as opt
    import scipy
    from scipy.optimize import minimize
except ImportError:
    print "You must install Python scipy first before running this program"

try:
    import numpy as np
except ImportError:
    print "You must install Python numpy first before running this program"

'''function f(x) = sin(x)'''
def f(x):
    print x
    #return -x**(2)
    return math.sin(x)

'''
check here for fmin_l_bgfs_b docs : https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_l_bfgs_b.html#scipy.optimize.fmin_l_bfgs_b
and what params need to used.

or you can take a look at here : https://docs.scipy.org/doc/scipy/reference/optimize.html for other method and algorithm
'''
initial_guess = 1.0

minbound = -9
maxbound = 9

max_bounds_area = (minbound,maxbound)
max_x = opt.fmin_l_bfgs_b(lambda x: -f(x), initial_guess, bounds=[(max_bounds_area)],approx_grad=True)

# I want to plot the result. I try this but I get TypeError: only length-1 arrays can be converted to Python scalars
t = np.arange(minbound, maxbound, initial_guess)
s = f(t)
plt.plot(t, s)
plt.show()

1 Answer 1

3

The math library can not operate on numpy arrays, you must use the functions implemented in numpy.

Must be change

return math.sin(x)

to

return np.sin(x) 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, it works. But how can I make it with smooth curve?
Has smaller to initial_guess, is the step that is used to plot. ie initial_guess=0.1
thanks it work with t = np.arange(minbound, maxbound, 0.1). really thanks I appreciate it.
I need to wait it for 5 minutes to accept this as correct answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.