Logiciel libre de géométrie, d'analyse et de simulation multiplateforme par Yves Biton

Accueil Tutoriels l’API de MathGraph32

Programming a figure in Python : The Newton method

modification vendredi 23 avril 2024.

Toutes les versions de cet article : [English] [français]



Since version 7.9.1 MathGraph32 allows the user to add objects to a figure using Python language.

First advanced example : We draw the curve of a function, we create a point linked to the x-axis (in fact a line at the same position) and we create a sequence of 50 tangents using Newton method starting with the linked point.
You can see that the figure you get is dynamical.
The derivative is a formal derivate calculated by MathGraph32.
For the figure to be dynamical, we have to create MathGraph32 objects in function newton.
You will find at the bottom of this page two other examples of code, but n the second one, the figure s not dynamical (the tangents are not updated when you capture point L)
In the last example, you will notice that using print in the Python code get the result in frame Output of the execution.
If you modify the Python code, click on button Execute to get this new code executed.

Other example of code to get the same result :

from mathgraph import *
# ne pas modifier la ligne ci-dessus
def newton(x, prof):
   t = getCalcName(x)
   form1 = 'f(t)'
   yx = addCalc('yx' + str(prof), form1.replace('t', t))
   form2 = 'g(t)'
   m = addCalc('m' + str(prof), form2.replace('t',t))
   pt1 = addPointXY(x, yx)
   pt2 = addPointXY(x, 0)
   addSegment(pt1, pt2, 'grey', '.')
   addLineAx(pt1, m, '', 'green', '.')
   form3 = '-f(t)/g(t) + t'
   x0 = addCalc('x' + str(prof) + '0', form3.replace('t', t))
   if (prof > 0):
       newton(x0, prof - 1)

setAngleUnity('radian')
zoomFig(0, 0, 2)
formula = 'exp(x)-2'
f = addFunc('f', formula)
courbe = addCurve(f, 500)
g = addDerivative('f', 'g')
axex = addLineAB('O', 'I')
setHidden(axex)
M = addLinkedPointLine(axex, 2, 0, 'M')
xM = addXMeasure(M, 'xM')
newton(xM, 50)

Example of non dnamical code :

from mathgraph import *
# ne pas modifier la ligne ci-dessus
# afin de pouvoir utiliser les fonctions mathgraph, par exemple
# A = addPointXY(3, 3, 'A')
setAngleUnity('radian')
formula = 'exp(x)-2'
ff = addFunc('f', formula)
def f(x):
   return getFuncImage(ff, x)
courbe = addCurve('f', 500)
gg = addDerivative('f', 'g')
def g(x):
   return getFuncImage(gg, x)
def newton(x, prof):
   yx = f(x)
   m = g(x)
   print(m)
   pt = addPointXY(x, yx)
   addLineAx(pt, m, '', 'green', '.')
   x0 = -f(x)/g(x) + x
   if (prof > 0):
       newton(x0, prof - 1)
axex = addLineAB('O', 'I')
setHidden(axex)
M = addLinkedPointLine(axex, 2, 0, 'M')
xM = addXMeasure(M, 'xM')
print(getValue(xM))
newton(getValue(xM), 5)