170+的阶乘
每次我尝试求 171 的阶乘时,我都会得到 INF。 170 工作正常。是否可以在脚本中获得 171+ 的阶乘?如何? 我的功能:
function factorial($n) {
if ($n == 0) return 1;
return $n * factorial($n - 1);
}
everytime I try to get the factorial of 171, I get INF. 170 works fine. Is it possible to get the factorial of 171+ in a script? How?
My function:
function factorial($n) {
if ($n == 0) return 1;
return $n * factorial($n - 1);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您处理非常大的数字,则需要使用允许您执行此操作的扩展程序。
有 BCMath ( http://www.php.net/manual/en/book. bc.php) 和 GMP ( http://www.php .net/manual/en/book.gmp.php)。
If you deal with very large numbers, you'll need to use an extension that allows you to do that.
There's BCMath ( http://www.php.net/manual/en/book.bc.php) , and GMP ( http://www.php.net/manual/en/book.gmp.php ).
您必须使用 BC Math 或 GNU MP 扩展。 PHP 不提供任何用于高值或高精度操作 OOTB 的工具。
You'll have to use BC Math or GNU MP extension. PHP doesn't provide any tools for high-values or high-precision operations OOTB.
确实,你的功能很好。我认为 PHP 缺乏这种精确性。我在 python 中得到了值(顺便说一句,这是正确的)
really though, your function is fine. I think PHP lacks that kind of precision. I got the value (it is correct btw) in python
您可能会得到一个超过 32 位机器中最大双精度浮点数的值 (
~10^308
)。 170!阶乘是~7.25741562 × 10^307
,然而,它就在这个之下,171!更大。最好的选择是使用 EboMike 或 Crozin 在其答案中推荐的库之一。You are probably getting a value that exceeds the maximum double precision float in a 32-bit machine (
~10^308
). 170! factorial is~7.25741562 × 10^307
which is just under that, however, 171! is larger. Your best bet is to use one of the libraries EboMike or Crozin recommends in their answers.对于大的n,你可以计算n!使用斯特林近似,速度非常快,误差很小。看看这篇文章;它对函数进行了分析,并提供了一些示例代码:
http://thirdbrothers。 org/brendan/blog/stirlings-approximation-formula-clojure/
For large n, you can compute n! very quickly with little error using Stirling's approximation. Take a look at this post; it has an analysis of the function and some sample code:
http://threebrothers.org/brendan/blog/stirlings-approximation-formula-clojure/
这个数字比 32 位所能容纳的数字还要大。如果您在 64 位计算机上运行相同的代码,那么它应该可以工作。
It's a bigger number than you can hold using 32-bits. If you run the same code on a 64-bit computer then it should work.