Is there something that's larger than any numbers in PHP?

百般思念 提交于 2019-12-19 19:55:09

问题


I need to simulate a ∞ in PHP.

So that min(∞,$number) is always $number.


回答1:


I suppose that, for integers, you could use PHP_INT_MAX , the following code :

var_dump(PHP_INT_MAX);

Gives this output, on my machine :

int 2147483647


But you have to be careful ; see Integer overflow (quoting) :

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

And, from the Floating point numbers documentation page :

The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

Considering the integer overflow, and depending on your case, using this kind of value might be a better (?) solution...




回答2:


Use the constant PHP_INT_MAX.

http://php.net/manual/en/language.types.integer.php




回答3:


You could potentially use the PHP_INT_MAX constant (click for PHP manual docs).

However, you may want to think about whether you really need to use it - it seems like a bit of an odd request.




回答4:


PHP actually has a predefined constant for "infinity": INF. This isn't true infinity, but is essentially the largest float value possible. On 64-bit systems, the largest float is roughly equal to 1.8e308, so this is considered to be equal to infinity.

$inf = INF;
var_dump(min($inf,PHP_INT_MAX)); // outputs int(9223372036854775807)
var_dump(min($inf,1.79e308)); // outputs float(1.79E+308)
var_dump(min($inf,1.799e308)); // outputs float(INF)
var_dump(min($inf,1.8e308)); // outputs float(INF)
var_dump($inf === 1.8e308); // outputs bool(true)

Note, any number with a value larger than the maximum float value will be cast to INF. So therefore if we do, var_dump($inf === 1e50000);, this will also output true even though the maximum float is less than this.




回答5:


I suppose, assuming this is an integer, you could use PHP_INT_MAX constant.




回答6:


min($number, $number + 1) ??




回答7:


In Perl you can use

$INF = 9**9E9;

which is larger than any value you can store in IEEE floating point numbers. And that really works as intended: any non-infinite number will be smaller than $INF:

$N < $INF

is true for any "normal" number $N.

Maybe you use it in PHP too?




回答8:


min($number,$number) is always $number (also true for max() of course).




回答9:


If your only concern is comparison function then yes, you can use array(), it will be always larger then any number

like

echo min(array(), 9999999999999999);

or

if (array() > 9999999999999999) {
  echo 'array won';
} else {
  echo 'number won';
}


来源:https://stackoverflow.com/questions/1900360/is-there-something-thats-larger-than-any-numbers-in-php

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