nan php что это

Математические функции

Содержание

User Contributed Notes 35 notes

And the reason I needed a Factorial function is because I there were no nPr or nCr functions native to PHP, either.

If you’re an aviator and needs to calculate windcorrection angles and groundspeed (e.g. during flightplanning) this can be very useful.

You can probably write these lines more beautiful, but they work!

Wouldn’t the following function do the same but a lot easier than the one in the comment before?

For people interest in Differential Equations, I’ve done a function that receive a string like: x^2+x^3 and put it in
2x+3x^2 witch is the differantial of the previous equation.

I know this is not optimal but i’ve done this quick 🙂
If you guys have any comment just email me.
I also want to do this fonction In C to add to phpCore maybe soon.
Patoff

Another ordinal method, which does not involve utilizing date functions:

Please note that shorter is not always better
(meaning that really short faculty implementation above).

In my opinion, a clearer way to code this is, including a check
for negative or non-integer values.

In order to calculate the faculty of a positive integer,
an iterative way (which might be harder to understand)
is usually a bit faster, but I am using it only for small
values so it is not really important to me:

I was looking for a truncate function. Not finding one, I wrote my own. Since it deals with everything as a number, I imagine it’s faster than the alternative of using string functions. HTH.

//provide the real number, and the number of
//digits right of the decimal you want to keep.

here is an algorithm to calculate gcd of a number. This is Euclid algorithm i was studying in Maths. I’ve converted it in php for the fun.

To add to what Cornelius had, I have written a function that will take an array of numbers and return the least common multiple of them:

Occasionally a user must enter a number in a form. This function converts fractions to decimals and leaves decimals untouched. Of course, you may wish to round the final output, but that is not included here.

Here’s yet another greatest common denominator (gcd) function, a reeeeally small one.

function gcd($n,$m)<
if(!$m)return$n;return gcd($m,$n%$m);
>

It works by recursion. Not really sure about it’s speed, but it’s really small! This won’t work on floating point numbers accurately though. If you want a floating point one, you need to have at least PHP 4, and the code would be

function gcd($n,$m)<
if(!$m)return$n;return gcd($m,fmod($n,$m));
>

Источник

Различные типы чисел в PHP

Работая с числамт следует отметить, что PHP обеспечивает автоматическое преобразование типов данных. Например, если вы присвоите переменной целочисленное значение, тип этой переменной автоматически будет целым числом. На следующей строке кода вы можете назначить строку той же переменной и её тип изменится на строку. Это автоматическое преобразование иногда может нарушить ваш код.

Целые числа PHP

Основные правила определения целого числа:

Функции PHP для проверки целочисленного типа переменной:

Проверим, является ли тип переменной целым числом:

Пример

Результат выполнения кода:

Число с плавающей точкой

В PHP есть следующие функции для проверки того, является ли переменная типом float :

Пример

Результат выполнения кода:

PHP Бесконечность

В PHP любое числовое значение выше PHP_FLOAT_MAX на платформе считается бесконечным.

Функция PHP var_dump() возвращает тип данных и значение:

Пример

Результат выполнения кода:

Специальное значение NAN

Функция PHP var_dump() возвращает тип данных и значение:

Пример

Результат выполнения кода:

Числовые строки в PHP

PHP будет неявно использовать любую действительную числовую строку для числа, когда возникнет необходимость. Следующие примеры помогут вам лучше понять этот процесс:

Пример

Результат выполнения кода:

В предпоследнем случае шестнадцатеричная строка «0xfedd24» не преобразуется в ее десятичное значение потому, что PHP 7 не считает ее допустимой числовой строкой.

Примечание: Примечание: Начиная с PHP 7.0 функция is_numeric() возвращает значение FALSE для числовых строк в шестнадцатеричной форме (например, «0xfedd24» ), поскольку они больше не считаются числовыми строками.

Приведение строк и чисел с плавающей точкой к целым числам

Иногда вам будет нужно преобразовать числовое значение в другой тип данных. В PHP имеется множество функций и методов для этих целей. В большинстве случаев приведение будет выполнено неявно и вам не придется беспокоиться об этом. Но, если вам нужно сделать преобразование, используйте методы, приведенные ниже.

Источник

PHP Числа

В этой главе мы подробно рассмотрим целые числа (integer), числа с плавающей запятой (float) и числовые строки (number string).

PHP Числа

В PHP следует обратить внимание на то, что он обеспечивает автоматическое преобразование типов данных.

Таким образом, если вы назначите целочисленное значение переменной, тип этой переменной автоматически будет целым числом. Затем, если вы назначите строку для той же переменной, тип изменится на строку.

Это автоматическое преобразование может иногда нарушать ваш код.

Еще одна важная вещь, которую нужно знать, это то, что даже если 4 * 2.5 равно 10, результат сохраняется как float, потому что один из операндов является float (2.5).

Вот несколько правил для целых чисел:

PHP имеет следующие функции, чтобы проверить, является ли тип переменной целочисленным (integer):

Пример

Проверить, является ли тип переменной целочисленным:

Тип данных с плавающей запятой обычно может хранить значение до 1.7976931348623E + 308 (зависит от платформы) и может иметь максимальную точность 14 цифр.

PHP имеет следующие функции для проверки, является ли тип переменной float:

Пример

Проверьте, является ли тип переменной float:

Числовое значение, большее чем PHP_FLOAT_MAX считается бесконечным.

PHP имеет следующие функции для проверки, является ли числовое значение конечным или бесконечным:

Однако PHP функция var_dump() возвращает тип данных и значение:

Пример

Проверить, является ли числовое значение конечным или бесконечным:

NaN используется для невозможных математических операций.

PHP имеет следующие функции для проверки, если значение не является числом:

Однако PHP функция var_dump() возвращает тип данных и значение:

Пример

Неверный расчет вернет значение NaN:

PHP функция is_numeric() может использоваться для определения, является ли переменная числовой. Функция возвращает true, если переменная является числом или числовой строкой, в противном случае false.

Пример

Проверить, является ли переменная числовой:

Примечание: Начиная из PHP 7.0: функция is_numeric() вернет FALSE для числовых строк в шестнадцатеричной форме (например, 0xf4c3b00c), так как они больше не рассматриваются как числовые строки.

PHP Приведение string и float к целым числам (integer)

Иногда необходимо преобразовать числовое значение в другой тип данных.

Функции (int), (integer) или intval() часто используются для преобразования значения в целое число.

Источник

Предопределённые константы

Перечисленные ниже константы всегда доступны как часть ядра PHP.

Математические константы

КонстантаЗначениеОписаниеДоступна с версии
M_PI3.14159265358979323846число Пи
M_E2.7182818284590452354число Эйлера (e)
M_LOG2E1.4426950408889634074log_2 e
M_LOG10E0.43429448190325182765lg e
M_LN20.69314718055994530942ln 2
M_LN102.30258509299404568402ln 10
M_PI_21.57079632679489661923Пи/2
M_PI_40.78539816339744830962Пи/4
M_1_PI0.318309886183790671541/Пи
M_2_PI0.636619772367581343082/Пи
M_SQRTPI1.77245385090551602729sqrt(Пи)PHP 5.2.0
M_2_SQRTPI1.128379167095512573902/sqrt(Пи)
M_SQRT21.41421356237309504880sqrt(2)
M_SQRT31.73205080756887729352sqrt(3)
M_SQRT1_20.707106781186547524401/sqrt(2)
M_LNPI1.14472988584940017414Натуральный логарифм числа пи
M_EULER0.57721566490153286061Постоянная Эйлера
PHP_ROUND_HALF_UP1Округление к большему целому
PHP_ROUND_HALF_DOWN2Округление к меньшему целому
PHP_ROUND_HALF_EVEN3Округление к чётному числу
PHP_ROUND_HALF_ODD4Округление к нечётному числу
NANNAN (тип float)Не является числом (Not A Number)
INFINF (тип float)Бесконечность

User Contributed Notes 7 notes

I just learnt of INF today and found out that it can be used in comparisons:

Источник

Точность чисел с плавающей точкой

Числа с плавающей точкой имеют ограниченную точность. Хотя это зависит от операционной системы, в PHP обычно используется формат двойной точности IEEE 754, дающий максимальную относительную ошибку округления порядка 1.11e-16. Неэлементарные арифметические операции могут давать большие ошибки, и, разумеется, необходимо принимать во внимание распространение ошибок при совместном использовании нескольких операций.

Так что никогда не доверяйте точности чисел с плавающей точкой до последней цифры и не проверяйте напрямую их равенство. Если вам действительно необходима высокая точность, используйте математические функции произвольной точности и gmp-функции.

«Простое» объяснение можно найти в » руководстве по числам с плавающей точкой, которое также называется «Why don’t my numbers add up?» («Почему мои числа не складываются?»)

Преобразование в число с плавающей точкой

Из строк

Если строка содержит число или ведущую числовую последовательность, тогда она будет преобразована в соответствующее значение с плавающей точкой, в противном случае она преобразуется в ноль ( 0 ).

Из других типов

Для значений других типов преобразование выполняется путём преобразования значения сначала в целое число ( int ), а затем в число с плавающей точкой ( float ). Смотрите Преобразование в целое число для получения дополнительной информации.

Поскольку определённые типы имеют неопределённое поведение при преобразовании в целое число ( int ), то же самое происходит и при преобразовании в число с плавающей точкой ( float ).

Сравнение чисел с плавающей точкой

Как указано выше, проверять числа с плавающей точкой на равенство проблематично из-за их внутреннего представления. Тем не менее, существуют способы для их сравнения, которые работают несмотря на все эти ограничения.

Для сравнения чисел с плавающей точкой используется верхняя граница относительной ошибки при округлении. Эта величина называется машинной эпсилон или единицей округления (unit roundoff) и представляет собой самую маленькую допустимую разницу при расчётах.

= 1.23456789 ;
$b = 1.23456780 ;
$epsilon = 0.00001 ;

User Contributed Notes 36 notes

PHP thinks that 1.6 (coming from a difference) is not equal to 1.6. To make it work, use round()

var_dump(round($x, 2) == round($y, 2)); // this is true

While the author probably knows what they are talking about, this loss of precision has nothing to do with decimal notation, it has to do with representation as a floating-point binary in a finite register, such as while 0.8 terminates in decimal, it is the repeating 0.110011001100. in binary, which is truncated. 0.1 and 0.7 are also non-terminating in binary, so they are also truncated, and the sum of these truncated numbers does not add up to the truncated binary representation of 0.8 (which is why (floor)(0.8*10) yields a different, more intuitive, result). However, since 2 is a factor of 10, any number that terminates in binary also terminates in decimal.

I’d like to point out a «feature» of PHP’s floating point support that isn’t made clear anywhere here, and was driving me insane.

Will fail in some cases due to hidden precision (standard C problem, that PHP docs make no mention of, so I assumed they had gotten rid of it). I should point out that I originally thought this was an issue with the floats being stored as strings, so I forced them to be floats and they still didn’t get evaluated properly (probably 2 different problems there).

To fix, I had to do this horrible kludge (the equivelant of anyway):

if (round($a,3)>=round($b,3)) echo «blah!»;

THIS works. Obviously even though var_dump says the variables are identical, and they SHOULD BE identical (started at 0.01 and added 0.001 repeatedly), they’re not. There’s some hidden precision there that was making me tear my hair out. Perhaps this should be added to the documentation?

Concider the following:

19.6*100 cannot be compaired to anything without manually
casting it as something else first.

Rule of thumb, if it has a decimal point, use the BCMath functions.

The ‘floating point precision’ box in practice means:

This returns 0.1 and is the workaround we use.

So, that’s all lovely then.

In some cases you may want to get the maximum value for a float without getting «INF».

var_dump(1.8e308); will usually show: float(INF)

I wrote a tiny function that will iterate in order to find the biggest non-infinite float value. It comes with a configurable multiplicator and affine values so you can share more CPU to get a more accurate estimate.

I haven’t seen better values with more affine, but well, the possibility is here so if you really thing it’s worth the cpu time, just try to affine more.

Best results seems to be with mul=2/affine=1. You can play with the values and see what you get. The good thing is this method will work on any system.

Beware of NaN and strings in PHP.
In other languages (and specifically in Javascript) math operations with non-numerical strings will result in NaN, while in PHP the string is silently converted to 0.

is_nan(‘hello, string’); // false

gives the impression that the string is a valid number.

Be careful when using float values in strings that are used as code later, for example when generating JavaScript code or SQL statements. The float is actually formatted according to the browser’s locale setting, which means that «0.23» will result in «0,23». Imagine something like this:

This would result in a different result for users with some locales. On most systems, this would print:

but when for example a user from Germany arrives, it would be different:

which is obviously a different call to the function. JavaScript won’t state an error, additional arguments are discarded without notice, but the function doBar(a) would get 0 as parameter. Similar problems could arise anywhere else (SQL, any string used as code somewhere else). The problem persists, if you use the «.» operator instead of evaluating the variable in the string.

So if you REALLY need to be sure to have the string correctly formatted, use number_format() to do it!

To simply convert 32 bits float from hex to float:

To compare two numbers use:

In the gettype() manual, it says «(for historical reasons «double» is returned in case of a float, and not simply «float») «.

However, I think that internally PHP sometimes uses the C double definition (i.e. a double is twice the size of a float/real). See the example below:

(The strrev_x-bin2hex combination is just to give printable characters.)

Given that PHP treats doubles and floats identically, I’d expected the same string as output, however, the output is:

double pack
string(16) «3ff999999999999a» //Here you see that there is a minute difference.
string(16) «3ff9999999999998»
float pack
string(8) «3fcccccd» //. which doesn’t exist here
string(8) «3fcccccd»

Convert a hex string into a 32-bit IEEE 754 float number. This function is 2 times faster then the below hex to 32bit function. This function only changes datatypes (string to int) once. Also, this function is a port from the hex to 64bit function from below.

But, please don’t use your own «functions» to «convert» from float to binary and vice versa. Looping performance in PHP is horrible. Using pack/unpack you use processor’s encoding, which is always correct. In C++ you can access the same 32/64 data as either float/double or 32/64 bit integer. No «conversions».

PHP switches from the standard decimal notation to exponential notation for certain «special» floats. You can see a partial list of such «special» values with this:

I have to be honest: this is one of the strangest things I have seen in any language in over 20 years of coding, and it is a colossal pain to work around.

Just another note about the locales. Consider the following code:

convert 32bit HEX values into IEEE 754 floating point
= «C45F82ED» ;

I’ve just come across this issue with floats when writing a function for pricing. When converting from string to a float, with 2 digits of precision, the issue with comparing floats can pop up and give inconsistent results due to the conversion process.

An easier way rather than relying on the mentioned epsilon method is to use number_format (at least for me as I’ll remember it!).

Example function that can return an unexpected result:

if((float)$a == (float)$b) <
echo true;
> else <
echo false;
>

echo’s false in this example.

Using number format here to trim down the precision (2 point precision being mostly used for currencies etc, although higher precisions should be correctly catered for by number_format), will return an expected result:

if(number_format((float)$a, 2) == number_format((float)$b, 2)) <
echo true;
> else <
echo false;
>

Correctly echo’s true.

My BIN to FLOAT (IEEE754), the first one doesn’t work for me:

As «m dot lebkowski+php at gmail dot com» (http://www.php.net/language.types.float#81416) noted 9 comments below :

When PHP converts a float to a string, the decimal separator used depends on the current locale conventions.

Calculations involving float types become inaccurate when it deals with numbers with more than approximately 8 digits long where ever the decimal point is. This is because of how 32bit floats are commonly stored in memory. This means if you rely on float types while working with tiny fractions or large numbers, your calculations can end up between tiny fractions to several trillion off.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *