-7

I'm trying to find the number of bisections Python takes to produce the root of a function. For example, if I have the code:

import math
a=1
b=2
def f(x):
    return x**3+x-7
while b-a>0.001:
    c=(a+b)/2
    if f(a)*f(c)>0:
         a=c
    else:
         b=c
print(c)

This code will simply produce the desired answer. I would like to know how many times Python performed the bisection method and what were the values each time.

  • 2
    you can set a count variable which will count each time bisection method is used. Also add print to print the values that you desire to print each time. – Rakholiya Jenish Jun 06 '15 at 20:12
  • import math a=1 b=2 count = 0 def f(x): return x**3+x-7 while b-a>0.001: count += 1 c=(a+b)/2 if f(a)*f(c)>0: a=c else: b=c print(c) – Pralhad Narsinh Sonar Jun 06 '15 at 20:15

1 Answers1

2

You can use some profiler. For example line_profiler. You can install it simply:

pip install line_profiler

Look here: How can I profile python code line-by-line?

Community
  • 1
  • 1
Marcin
  • 137
  • 1
  • 5