Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - GMP and floating point numbers?

Tags:

php

gmp

The following code outputs 0, which isn't correct:

$r = gmp_pow(gmp_init('-1.7976931348623157'), 308);
echo gmp_strval($r);

I was under the impression that the GMP library was capable of handling floating point numbers, or have I made a mistake in the code?

like image 386
Matty Avatar asked Aug 05 '11 02:08

Matty


People also ask

What is PHP GMP?

GMP stands for GNU Multiple Precision Arithmetic Library (GMP). GMP is a library supported in PHP that allows you to do mathematical operations on signed integers, rational numbers, and floating point numbers. GMP has a rich collection of functions that helps to perform complex mathematical operations on big numbers.

Does PHP have float?

In PHP, the Float data type is used to set fractional values. A float is a number with a decimal point and can be extended to exponential form. Float is also called a floating-point number. Various ways to represent float values are 3.14, 4.75, 5.88E+20, etc.

What is PHP float max?

PHP Floats The float data type can commonly store a value up to 1.7976931348623E+308 (platform dependent), and have a maximum precision of 14 digits.

What are floating point numbers?

A floating point number, is a positive or negative whole number with a decimal point. For example, 5.5, 0.25, and -103.342 are all floating point numbers, while 91, and 0 are not. Floating point numbers get their name from the way the decimal point can "float" to any position necessary.


1 Answers

GMP library was capable of handling floating point numbers,

It's not. You can test that with:

echo gmp_strval(gmp_init('18')); // 18
echo gmp_strval(gmp_init('1.8')); // 0

Now, what you could do is use BCMath instead:

$num = bcpow('-1.7976931348623157', '308');
echo $num;
echo floatval($num); // for a "prettier" format
like image 79
NullUserException Avatar answered Oct 27 '22 17:10

NullUserException