Large multiplication output coming out negative in Ruby

青春壹個敷衍的年華 提交于 2019-12-10 17:23:45

问题


I wrote some code that is supposed to sum n^n for 1 <= n <= 1000. Here's the code:

sum = 0
(1..1000).each do |n|
  sum += n**n
  puts "n = #{n}, sum = #{sum}"
end

For some reason, the output is coming out negative after number 28:

n = 29, sum = -2015400977700573523892329442490139437391867

Any idea why this is happening?


回答1:


Looks like this was a bug in 1.8.7 that was fixed by patch 358: Exponentiation in Ruby 1.8.7 Returns Wrong Answers

(The result of a power computation in numeric.c wasn't declared as volatile before this commit, after which overflow behavior seems to have been fixed.)



来源:https://stackoverflow.com/questions/13130557/large-multiplication-output-coming-out-negative-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!