0

I have the following simple python program to find roots of equation with the bisection method:

from numpy import exp
#
def fun(x):
  return 5.0+4.0*x-exp(x)
#
a=3
b=10.0
eps=1.0e-15
#
fa=fun(a)
fb=fun(b)
#
if fa*fb>0:
  print("wrong interval!!!",fa,fb)
  exit()
#
iter=1
while (b-a)>eps:
  c=(a+b)/2.0
  fc=fun(c)
  if fc==0:
    print("x = ",c)
    exit()
  if fc*fa>0:
    a=c
    fa=fc
  else:
    b=c
    fb=fc
  iter+=1
#
print("x = ",c)
print("accuracy = ",'{:.2e}'.format(b-a))
print("f(",c,") =",fun(c))
print(iter," iterations needed")

If I put a in the wrong interval (like a=3) it says that it's the wrong interval, but it continues anyway giving (obviously) a wrong result and four lines of

ERROR:root:Invalid alias: The name less can't be aliased because it is another magic command.

Morover, the kernel dies (I'm using jupyter). Can you help me?

domx
  • 13
  • 1

2 Answers2

0

This might be because you need to add an else statement after the if statement is finished to say if it is false do this, else do the rest of the code.

AyanSh
  • 324
  • 1
  • 10
0

You should use sys.exit("optional custom message") instead of just exit()

This raises a SystemExit exception, while just exit() only makes sense in the context of the interpreter.

import sys
# logic here
if "something bad":
    sys.exit("optional custom message")

The difference is described in detail here! https://stackoverflow.com/a/19747562/4541045

ti7
  • 16,375
  • 6
  • 40
  • 68