Problem: Write a function to let the user calculate the value of a function f(x) at an arbitrary point x = a
- Input: a
- Output: value of the function f at x = a
Apply to calculate the value of f(x)= sqrt(x-2) at x=4.
My question: I don't know clearly the meaning of this problem. If we want to calculate the value of a function, we can assign a value we need and put it in a function without defining a function like this?
CodePudding user response:
Yes. You can use something like eval
. You don't actually need to define a function in your code. Instead, you can put it in a string and pass it to eval
.
Try something like this:
import math
a = int(input())
f = 'math.sqrt(x-2)'
x = a
print(eval(f))
You could change f
to any function, or even read f
from input as a string.
CodePudding user response:
You have a
as input and f(a)
as output, but the problem says define a function to apply f
on a
. So, instead of directly writing f(a)
you write eval_func(a)
that returns the same f(a)
.
import math
def eval_func(a):
x = a
return math.sqrt(x-2)
Run with input 4:
eval_func(4)
1.4142135623730951