dichotomie.py

Created by christian-mercat

Created on December 01, 2023

286 Bytes

Calcule la racine d’une fonction continue passée en argument, étant donnés deux bornes entre lesquels la fonction change de signe. Par exemple dichotomie(lambda x: cos(x)-x,0,3,1e-7) pour trouver x tel que cos(x)=x entre 0 et 3 à une précision de 1e-7.


from math import *
def dichotomie(f=lambda x: exp(x)-x**2,a=-1,b=1,e=1e-5):
  c=(a+b)/2
  if abs(b-a)<e:
    return c
  fa, fb, fc = map(f,[a,b,c])
  if fa*fb > 0:
    return None
  elif fa*fc > 0:
    return dichotomie(f,c,b,e)
  else:
    return dichotomie(f,a,c,e)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our <a href="https://www.numworks.com/legal/cookies-policy/">cookies policy</a>.