我有python scipy优化函数f(x)= sin(x),我想绘制结果。我怎样才能做到这一点?我已经尝试过这段代码。但我收到此错误:TypeError: only length-1 arrays can be converted to Python scalars
这是我的代码:
'''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()
答案 0 :(得分:3)
import re
import os
source = open('title.txt')
text = source.read()
ment = re.findall(r'\w*ment+\w*', text)
ity = re.findall(r'\w*ity+\w*', text)
tion = re.findall(r'\w*tion+\w*', text)
age = re.findall(r'\w*age+\w*', text)
ance = re.findall(r'\w*ance+\w*', text)
ence = re.findall(r'\w*ence+\w*', text)
dom = re.findall(r'\w*dom+\w*', text)
ery = re.findall(r'\w*ery+\w*', text)
ry = re.findall(r'\w*ry+\w*', text)
ism = re.findall(r'\w*ism+\w*', text)
ness = re.findall(r'\w*ness+\w*', text)
hood = re.findall(r'\w*hood+\w*', text)
nominalizations = ment, ity, tion, age, ance, ence, dom, ery, ry, hood, ism,
ness
import docx
from docx import Document
from docx.text.run import Font
from docx.text.run import Run
from docx.enum.text import WD_COLOR_INDEX
doc = docx.Document('title.docx")
库无法在math
上运行,您必须使用numpy arrays
中实现的功能。
必须改变
numpy
到
return math.sin(x)