Why does Math.Log crash only inside my for loop?
I have the below code
A = 1.0
B = 0.20
N = 8.0
for i in 1..Total
t = Maxt * rand
x = A * Math.cos(t) / (Math.log(B*Math.tan(t/(2*N))))
y = A * Math.sin(t) / (Math.log(B*Math.tan(t/(2*N))))
end
If I comment out the For loop it executes fine and produces 1 of the results I want. If I don't comment out the for loop, it generates the below. I am a newbie with Ruby and am mainly curious why it only breaks when the for loop is present.
rubyfile.rb:22:in `log': Numerical argument out of domain - log (Errno::EDOM)
from rubyfile.rb:22
from rubyfile开发者_开发百科.rb:20:in `each'
from rubyfile.rb:20
Math.log
represents the logarithm function, which is undefined for negative numbers. Math.tan
, however, represents the tangent function, which can return negative numbers. So, if Math.tan
comes out to a negative number, the Math.log
will tell you that its argument is "out of domain", meaning that there is no logarithm for that number.
I'm betting the fact that your input is random means that, when you loop, you are far more likely to get that error than if you just run the script once. If you were the remove the loop then run the script multiple times, I bet you'd get that error eventually.
Find out why your math involves negative numbers when it shouldn't, and you're good to go :)
B*Math.tan(t/(2*N)))
will take negative values and log is undefined for x < 0
. As the error states, you're out of domain.
精彩评论