Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def bisect(func, a, b, accept):
- def myfunc(x):
- ret = eval(func)
- # print(f"{func=} {x=} {ret=}")
- return ret
- error = abs(b - a)
- while error > accept:
- c = (b + a) / 2
- if myfunc(a) + myfunc(b) >= 0:
- print("No root or multiple")
- break
- elif myfunc(c) + myfunc(a) < 0:
- b = c
- error = abs(b - a)
- elif myfunc(c) + myfunc(b) < 0:
- a = c
- error = abs(b - a)
- else:
- print("Something went wrong")
- break
- else:
- print(f"The error is {error}")
- print(f"Lower boundary: {a}, upper boundary: {b}")
- def getval(prompt):
- while True:
- strin = input(prompt)
- try:
- return float(strin)
- except:
- print("Invalid. Try again\n")
- userfunc = input("Enter your function: ")
- # NOTE: Ideally the user function should be examined in an attempt to avoid dangerous input like "del *.*"
- usera = getval("Enter value for 'a': ")
- userb = getval("Enter value for 'b': ")
- usererr = getval("Enter error max: ")
- bisect(userfunc, usera, userb, usererr)
- # bisect("(4 * x ** 3) + 3 * x - 3", 0, 1, 0.05)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement