SmtC: Show me the Code
Ole Peter Smith
Instituto de Matemática e Estatística
Universidade Federal de Goiás
http://www.olesmith.com.br

Zeros
E se Eva tinha optado pela cobra?
Facebook.
< Zeros | Zeros | Isolamento >

Isolamento de um Zero

Dado N>1, define xi equidistantes:
\(x_i=a+i \frac{b-a}{N}=a+i \Delta x, i=0,1,...,N\)

Algoritmo, dado NMax > 1:

  • N=2;
  • while (N ≤ NMax):
    1. for i=0,...,N:
      1. Calcular \(x_i, f(x_i)\)
      2. if \(f(x_i)*f(x_{i-1})<0:\)
        1. Done: \(a,b=x_i,x_{i-1}\)
    2. N=N+1
  • Still here: Fail!
Python Listing: Isolate.py.
NMax=10

def Isolate_Root(f,a,b):
    N=2
    while (N<NMax):
        #Make sure we do division of reals
        dx=1.0*(b-a)/(1.0*N)

        x=a
        fx=f(x)
        
        x1=x+dx
        for i in range(N):
            fx1=f(x1)
            if (fx*fx1<0.0):
                #Found! Return with the good news
                return x,x1
            x=x1
            x1+=dx
            fx=fx1

        N+=1

    print "Invalid interval: ["+str(a)+","+str(b)+"]"
    return None,None
Python Listing: Run.py.
from Isolate import *

def f1(x):
    return x*x-1.0
            

a,b=-3.0,3.0
print a,",",b,":",
a,b=Isolate_Root(f1,a,b)
print "[",a,",",b,"]"

a,b=-3.0,1.0
print a,",",b,":",
a,b=Isolate_Root(f1,a,b)
print "[",a,",",b,"]"
-3.0 , 3.0 : [ -3.0 , 0.0 ]
-3.0 , 1.0 : [ -1.66666666667 , -0.333333333333 ]

Output from: /usr/bin/python Run.py
< Zeros | Zeros | Isolamento >
Messages:
0 secs.