Reputation: 340
My draft code for sin(x) maclaurin series:
def factorial(z)
if z == 0
1
else
z * factorial(z-1)
end
end
puts "Enter x"
x = gets.chomp
puts "Enter n"
n = gets.chomp
(0..Integer(n)).each do |n|
k = ((-1)**(n-1))*(Integer(x)**(2*n-1))/factorial(2*n-1)
puts k
end
This code worked well until I added the each
loop. Now I get stack level too deep (SystemStackError)
error.
Without the each
loop or /factorial(2*n-1)
part everything worked fine. I cannot figure out what am I missing.
Upvotes: 0
Views: 395
Reputation: 10018
All gets
values are strings.
You need to convert them in integer, like
puts "Enter x"
x = gets.chomp.to_i
puts "Enter n"
n = gets.chomp.to_i
And in next code you should not to use Integer(n)
, just simply use n
.
Also want to note, that you should try implement factorial without recursive function. It could also to raise stack level exception for large z
Upvotes: 0
Reputation: 44685
Here:
factorial(2*n-1)
For n == 0
(first iteration) this evaluates to factorial(-1)
. You might want to change your factorial method to:
def factorial(z)
if z <= 0
1
else
z * factorial(z-1)
end
end
Upvotes: 3