Wednesday, October 25, 2017

Adventures in Python: User-Entry Function

Adventures in Python:  User-Entry Function

The following script allows the user to enter a function, including math functions (math.sqrt, math.sin, etc).  The function is entered as string and when calculation is needed, the eval function is called. 

Script:

# Program 010:  Asking for a function - Using Eval
# To generate a table

# allow for math functions
import math


# ask for the parameters
print('Generate f(x): You can use math. functions')
print('Such as math.sqrt, math.sin, math.exp, etc.')
print('Remember the default angle measure is radians.')
print('Use math.pi for \u03C0')
# f(x) and parameters will be entered as a string
fx = input('Please enter f(x): ')
# use float for end marks
beg = input('Beginning point:  ')
end = input('Ending point:  ')
step = input('Step: ')
# use eval to evaluate the parameters, turning them into floating numbers
beg = eval(beg)
end = eval(end)
step = eval(step)


print('BEGIN')

# since a floating number with begin, end, and step may be used,
# we must use a while loop instead of a for loop
k = beg
while k<=end:
    # function evaluation
    x = k
    y = eval(fx)
    #  print the data to six decimal places
    x = round(x,6)
    y = round(y,6)
    print(x,',',y)
    print('-----')
    # use += for storage arithmetic
    k += step

# end of table
print('END')

Example:

f(x) = √(x^2 + 1) from x = 0 to x = 4, step 0.5

Result:

Generate f(x): You can use math. functions
Such as math.sqrt, math.sin, math.exp, etc.
Remember the default angle measure is radians.
Use math.pi for π
Please enter f(x): math.sqrt(x**2+1)
Beginning point:  0
Ending point:  4
Step: 0.5
BEGIN
0 , 1.0
-----
0.5 , 1.118034
-----
1.0 , 1.414214
-----
1.5 , 1.802776
-----
2.0 , 2.236068
-----
2.5 , 2.692582
-----
3.0 , 3.162278
-----
3.5 , 3.640055
-----
4.0 , 4.123106
-----
END

Pretty straight forward.  I hope you are enjoying this series on Python.  Until next time,

Eddie


This blog is property of Edward Shore, 2017