Advertisement
acclivity

pyEvalUserFunction

Apr 30th, 2022
1,027
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1.  
  2. def bisect(func, a, b, accept):
  3.  
  4.     def myfunc(x):
  5.         ret = eval(func)
  6.         # print(f"{func=}  {x=}  {ret=}")
  7.         return ret
  8.  
  9.     error = abs(b - a)
  10.  
  11.     while error > accept:
  12.         c = (b + a) / 2
  13.  
  14.         if myfunc(a) + myfunc(b) >= 0:
  15.             print("No root or multiple")
  16.             break
  17.  
  18.         elif myfunc(c) + myfunc(a) < 0:
  19.             b = c
  20.             error = abs(b - a)
  21.  
  22.         elif myfunc(c) + myfunc(b) < 0:
  23.             a = c
  24.             error = abs(b - a)
  25.  
  26.         else:
  27.             print("Something went wrong")
  28.             break
  29.     else:
  30.         print(f"The error is {error}")
  31.         print(f"Lower boundary: {a},  upper boundary: {b}")
  32.  
  33.  
  34. def getval(prompt):
  35.     while True:
  36.         strin = input(prompt)
  37.         try:
  38.             return float(strin)
  39.         except:
  40.             print("Invalid. Try again\n")
  41.  
  42.  
  43. userfunc = input("Enter your function: ")
  44. # NOTE: Ideally the user function should be examined in an attempt to avoid dangerous input like "del *.*"
  45.  
  46. usera = getval("Enter value for 'a': ")
  47. userb = getval("Enter value for 'b': ")
  48. usererr = getval("Enter error max: ")
  49. bisect(userfunc, usera, userb, usererr)
  50.  
  51. # bisect("(4 * x ** 3) + 3 * x - 3", 0, 1, 0.05)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement