Using python for finding the root of $f(x)=x^2-2x-3=0$ in the interval $[2,4]$

527 Views Asked by At

I'm a beginner program learner. this is my try. I'm not sure it's correct or not. Could you give me some help.

import math
def g(x):
    while x-f(x) != 0:
        x=f(x)
    print(float(x))
def f(x) :
    f = math.sqrt(2*x+3)
    return f
def main ():
    g(4)
main()
1

There are 1 best solutions below

2
On

This is definitely better in Stack Overflow. However, your code is correct, if a bit weird. It doesn't check whether the resulting root is in $[2, 4]$, and it doesn't do anything sensible if the iteration diverges.

Somewhat better in that it gives things vaguely sensible names:

def fixed_point(x, f, debug=True):
   while x != f(x):
      x = f(x)
      if debug:
        print(float(x))
   return x

def f(x):
  return math.sqrt(2*x+3)

if __name__ == '__main__':
  print(fixed_point(4, f))