asdas

Ruby code posted by asfd
created at 23 Nov 13:11

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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}"
}
1.27 KB in 5 ms with coderay