0

Im trying to do a program that calculates the integral of a function set by an user. I have problem with using the function set by the user. How do a use a function of x set by the user in the following code. I have tried to use a function called eval but Iam not sure how it works. Here is my code:

 function_def = eval(input("skriv in din funktion här:"))
 x = int(input("Från vilken punkt på x-axeln vill du mätta ifrån:"))
 x_stop = int(input("Från vilken punkt på x-axeln vill du mätta till:"))

 trapets = []
 x_width = 0.000001

 def height():
     return function_def


 while x <= x_stop:
     x += x_width
     trapets.append(height() * x_width)

 int_sum = sum(trapets)
 print('Integralens värde är ' + str(int_sum))
  • With `eval`, the user has to enter a valid lambda expression if you want a function you can call. Without `eval`, you have to write your own parser and evaluator. – chepner May 01 '20 at 20:08
  • Does this answer your question? [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – AMC May 01 '20 at 21:56

0 Answers0