Skip to content

Instantly share code, notes, and snippets.

@konalegi
Created April 13, 2015 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save konalegi/572d1a7f444b204caa54 to your computer and use it in GitHub Desktop.
Save konalegi/572d1a7f444b204caa54 to your computer and use it in GitHub Desktop.
numerical method
def f(x)
x**3 - 0.2 * x**2 - 0.2 * x - 1.2
# x**4 + 2 * x**3 - x - 1
end
def calc(x_min, x_max, old = 9999, accuracy = 0.0001)
found_x = (x_min + x_max) / 2
p found_x
val = f((x_max + x_min)/2)
return found_x if (old - found_x).abs < accuracy
if val == 0
return found_x
else
if f(x_min) * f(found_x) < 0
calc(x_min, found_x, found_x)
elsif f(found_x) * f(x_max) < 0
calc(found_x, x_max, found_x)
end
end
end
p calc(1.0, 2.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment