0

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
4

2 に答える 2

7

Math.log対数関数を表します。これは、負の数に対しては定義されていません。Math.tanただし、は正接関数を表し、負の数を返すことができます。したがって、Math.tan負の数にMath.logなると、その引数は「ドメイン外」であることがわかります。つまり、その数の対数はありません。

入力がランダムであるという事実は、ループしたときに、スクリプトを1回実行した場合よりも、そのエラーが発生する可能性がはるかに高いことを意味していると思います。ループを削除してからスクリプトを複数回実行した場合、最終的にはそのエラーが発生するはずです。

あなたの数学がそうではないのに負の数を含む理由を見つけてください、そしてあなたは行ってもいいです:)

于 2011-07-02T18:29:26.653 に答える
4

B*Math.tan(t/(2*N)))は負の値を取り、ログは。に対して未定義ですx < 0。エラーが示すように、あなたはドメイン外です。

于 2011-07-02T18:29:19.337 に答える