Created
April 1, 2017 21:16
-
-
Save rafael-fernandes/386ca95db3492655a0344871b204d609 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sign(x) | |
return '+' if x >= 0 | |
return '-' | |
end | |
# Calcula f(x) | |
def f(x) | |
x ** 3 + x - 1 | |
end | |
# Precisao | |
e = 0.00000000000005 | |
# Valores dos extremos do intervalo | |
a = 0.0 | |
b = 1.0 | |
# Numero da iteracao | |
k = 0 | |
# Numero de iteracoes | |
i = (Math.log(b-a)/Math.log(2) - Math.log(e)/Math.log(2)).ceil | |
puts "Iterações: #{i}" | |
sleep(1) | |
puts "k\ta_i\tf(a_i)\tc_i\tf(c_i)\tb_i\tf(b_i)" | |
while (b - a).abs > e | |
c = (a + b)/2.0 | |
puts "#{k}\t#{a.round(4)}\t#{sign(f(a))}\t#{c.round(4)}\t#{sign(f(c))}\t#{b.round(4)}\t#{sign(f(b))}" | |
# sleep(0.25) | |
if f(c) == 0 | |
break | |
end | |
if f(a) * f(c) < 0 | |
b = c | |
else | |
a = c | |
end | |
k += 1 | |
end | |
raiz = (a + b)/2 | |
puts "Raiz aproximada: #{raiz}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment