Created
October 13, 2015 19:48
-
-
Save lukesarnacki/60e036c7a0cb1ce49639 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
class Maclaurin | |
attr_reader :x, :steps, :function | |
DERIVATIVE = { | |
"sin" => "cos", | |
"cos" => "-sin", | |
"-sin" => "-cos", | |
"-cos" => "sin", | |
"e" => "e" | |
} | |
FUNCTION_VALUE = { | |
"sin" => 0, | |
"cos" => 1, | |
"-cos" => -1, | |
"-sin" => 0, | |
"e" => 1 | |
} | |
def initialize(function, x, steps) | |
@x = x | |
@steps = steps | |
@function = function | |
end | |
def calculate | |
series(function, 0, 0) | |
end | |
def series(function, step, number) | |
return number if step > steps | |
number += (x**step) * FUNCTION_VALUE[function] / factorial(step).to_f | |
series(DERIVATIVE[function], step + 1, number) | |
end | |
def factorial(n) | |
f = 1; for i in 1..n; f *= i; end; f | |
end | |
end | |
# Przykladowe uzycie: | |
m1 = Maclaurin.new("e", 1.2, 9) | |
puts "e^1.2 ~= #{m1.calculate}" | |
m2 = Maclaurin.new("sin", 0.7, 5) | |
puts "sin(0.7) ~= #{m2.calculate}" | |
m3 = Maclaurin.new("cos", 0.3, 6) | |
puts "cos(0.3) ~= #{m3.calculate}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment