import math
import pylab
import sympy
def f1(x):
"""function representing a cosine variant function and returned"""
return math.cos(2 * math.pi * x) * math.exp(-x ** 2)
def f2(x):
"""function representing a log variant function and returned"""
return math.log(x + 2.2)
def positive_places(f, xs):
"""return a list of elements of xs that are positive when operated in by
f"""
list1 = []
for i in xs:
if f(i) > 0:
list1.append(i)
return list1
def create_plot_data(f, xmin, xmax, n):
"""returns a tuple (xs, ys) where xs and ys are two sequences,
each containing n numbers"""
xs = [xmin + i * ((xmax - xmin) / (n - 1)) for i in range(n)]
ys = [f(xs[i]) for i in range(n)]
return (xs, ys)
def myplot():
"""plots a graph of f1() and returns the graph"""
print(create_plot_data(f1, -2, 2, 1001))
(a1, b1) = create_plot_data(f1, -2, 2, 1001)
(a2, b2) = create_plot_data(f2, -2, 2, 1001)
pylab.plot(a1, b1, label='f1(x)')
pylab.plot(a2, b2, label='f2(x)')
pylab.xlabel('x')
pylab.ylabel('y')
pylab.legend()
pylab.grid()
pylab.savefig('plot.pdf')
pylab.savefig('plot.png')
pylab.show()
def find_cross():
return sympy.solve(math.cos(2 * math.pi * x) * math.exp(-x ** 2) - math.log(x + 2.2), x)
`
您好我试图定义一个函数,它将找到2个方程相等的正x值点:f1(x) = f2(x)
f1(x) = math.cos(2 * math.pi * x) * math.e ** (-x ** 2)
f2(x) = math.log(x + 2.2)
表示x = 0
和x = 0.5
之间的点
答案 0 :(得分:0)
使用SymPy时,您可以利用mpmath's root finder能力处理任意多位数字:
import mpmath
import sympy as sy
sy.init_printing()
mpmath.mp.dps = 30 # accuracy of 30 digits
# declare expressions:
x = sy.Symbol('x', real=True)
f1 = sy.cos(2*sy.pi*x) * sy.exp(-x**2)
f2 = sy.log(x + sy.Rational(22, 10))
g = f2 - f1 # f1 == f2 is equivalent to g == 0:
dg = g.diff(x) # 1. derivative needed by numeric root-finder
# generate numeric functions from SymPy expressions:
g_m, dg_m = (sy.lambdify(x, f_, modules="mpmath") for f_ in (g, dg))
# find the roots:
x_sln = mpmath.findroot(g_m, [0, 0.5], solver='secant', df=dg)
print("Intersection f1(x) == f2(x) is at x = {}".format(x_sln))
# => Intersection f1(x) == f2(x) is at x = 0.0922612383093564032487110560683
请注意,混合SymPy
,math
(和NumPy
)功能会产生不必要的副作用。