Title / Description
Code trueroot=1.0 Restults=Hash.new() def f(x) x**(3.0)-3.0*x**(2.0)+3.0*x-1 end def f1(x) 3.0*x**(2)-6.0**x+3.0 end def bisection(inta, intb, epsilon ) a, b = inta, intb c = (inta+intb)/2 eps = epsilon i=0 while(b - a > eps) do c = (a+b)/2 curval = f(c)*f(a) if (curval<=0) b=c else a=c end Restults[[1,i]]=c i+=1 end return c end def newton(init, inta, intb, epsilon) x = init d = f(x)/f1(x) i=0 while( d.abs > epsilon ) do x = x-d d=f(x)/f1(x) Restults[[2,i]] = x i+=1 end return x end def newton_simple(init, inta, intb, epsilon) x = init d = f(x)/((f(x+f(x))-f(x))/f(x)) i=0; while(d.abs > epsilon ) do x = x-d d = f(x)/((f(x+f(x))-f(x))/f(x)) Restults[[3,i]] = x i+=1 end return x end def secant(init1, init2, inta, intb, epsilon) x = init1 x1 = init2 x0 = init1 temp=epsilon+1; i=0 while( temp.abs > epsilon ) do temp = f(x1)*( (x1-x0)/(f(x1)-f(x0)) ) x = x1-temp x0 = x1 x1 = x Restults[[4,i]] = x i+=1 end return x end e=0.0001 p bisection(0,1.2,e) p newton(1.1 ,0,1.2,e) p newton_simple(0.6,0,1.2,e) p secant(0.6, 2, 0,1.2,e) Restults.sort.each {|x,y| puts "#{x[1]}. -->#{y} \t #{(trueroot-y).abs}" }
Author
Highlight as C C++ CSS Clojure Delphi ERb Groovy (beta) HAML HTML JSON Java JavaScript PHP Plain text Python Ruby SQL XML YAML diff code