提问人:Biktor123 提问时间:11/11/2023 最后编辑:Biktor123 更新时间:11/13/2023 访问量:54
根据用户输入定义任何数学函数
Define any mathematical function from user input
问:
我正在创建一个 python 代码,该代码从用户输入接收数学函数并使用 Newton-Raphson 方法查找指定函数的根。当我尝试在用户输入上使用“def”功能时,问题就出现了。 我需要的是一个指定的函数,然后我可以操作该函数并获取其导数,依此类推。 我试过查看其他人的类似问题,但找不到/不理解解决方案,所以请用简单的术语解释。 请注意,我对编程非常陌生。
这是我试图做的:
from math import *
f = input("Write your equation: ") #e.g. 2x^2+log(x)
f = f.replace('^', '**') #I can't find a way to switch out multiplication with "*"
#My original thought was to do something like this, but even with '*' and '**', it still dosen't work
def f(x):
return f
早些时候,我让它仅适用于多项式,使用以下方法:
f = input("Enter the polynomial: ")
f = f.replace('^', '**') #replaces exponentiating
f = f.replace('x', '*x') #replaces multiplication with *, but dosen't work if x is alone
f = f.replace('-*x', '-x') # ̌
f = f.replace('+*x', '+x') # fixes the above issue
if f.find("*") == 0: # ^
listf = list(f)
listf.pop(0)
f = "".join(listf)
def g(x, f):
f = f.replace('x', f"({str(x)})") #my solution to the original problem
return eval(f)
def g_prim(x): #defining the first derivative
h = 0.00001
return (g(x+h, f)-g(x, f))/h
def g_biss(x): #defining the second derivative
h = 0.00001
return (g_prim(x+h)-g_prim(x))/h
a = [] #list of maximas
for i in range(-50, 50, 5): #finds the maxima and adds ± 0.5
while abs(g_prim(i)) > 0.00001:
i = i - g_prim(i)/g_biss(i)
a.append(round(i+.5,3))
a.append(round(i-.5,3))
a = list(dict.fromkeys(a))
b = [] #list of roots
for a in a: #Newton-Raphson from every maxima(±0.5)
while abs(g(a, f)) > 0.00001:
a = a - g(a, f)/g_prim(a)
b.append(round(a,1))
b = list(dict.fromkeys(b))
print("The roots of the polynomial is:")
print(b)
答: 暂无答案
下一个:如何最大化多变量方程?
评论
sympy
(x-a)(x-b)(x-c)...(x-z)