根据用户输入定义任何数学函数

Define any mathematical function from user input

提问人:Biktor123 提问时间:11/11/2023 最后编辑:Biktor123 更新时间:11/13/2023 访问量:54

问:

我正在创建一个 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)
python 函数 数学 输入 微积分

评论

1赞 Gordon Gustafson 11/11/2023
“我需要的是一个指定的函数,然后我可以操作它并获取其的导数,依此类推”。只能调用 Python 函数。您可以采用 epsilon 近似的数值导数,但不能采用解析导数。不过,您可能想尝试使用 Pytorch,它是一个库,用于跟踪对“变量”所做的操作,该变量稍后可以在特定点评估分析导数的值。
3赞 cards 11/11/2023
使用 ,这里是一个用法示例。它有自己的字符串解析器,一旦你得到一个sympy对象,你就可以派生,找到根,...[所有用于符号操作的东西]sympy
0赞 Fredy 11/11/2023
只是一个想法:“for a in a:”这在 python 中是允许的吗?
0赞 Stef 11/11/2023
@Fredy 可以,但不是特别推荐。让我想起了这个谜语:简化为什么?(x-a)(x-b)(x-c)...(x-z)
1赞 Fredy 11/13/2023
@Stef我想到了“for a in a:”的含义,SO中有一篇关于此的文章,并且“for a[-1]在a:”中的变体非常有趣。感谢您在 2 条最新评论中澄清。我说“感觉”是因为我习惯了高度类型化的东西,也习惯了数学。这不是一个好词。在 80 年代,我记得使用了非常奇怪的代码行,乍一读时不是很容易理解。

答: 暂无答案