Define any mathematical function from user input

63 views Asked by At

Im creating a python code that receives a mathematical function from user input and finds the roots of the specified function using Newton-Raphson method. The problem emerges when I try to use "def" funcion on a user input. What I need is a specified function that I then can manipulate and take the derivate of and so on. I've tried looking at other peoples similar problems but can't find any/don't understand the solution so please explain in simple terms. Please note that I'm very new to programming.

This is what I tried to do:

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 

Earlier i got it to work for polynomials only using the folowing method:

  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)
0

There are 0 answers