1

using php, this code echo sprintf('%.9F',pow(3,47)); outputs 26588814358957501972480.000000000

where as other sites like this gives 3^47 = 26588814358957503287787. Is there any bug with PHP? How to resolve it?

btw, i'd like to know what is the maximum digit php can handle for calculation using pow,sprintf,fmod. Is it 300 digits?

Nok Imchen
  • 2,802
  • 7
  • 33
  • 59

2 Answers2

2

You need to use an external program or a PHP extension (library).

I've just tested it with BC Math and GMP using the bcpow()/gmp_pow() functions and it works perfectly:

<?php

// both output 26588814358957503287787
echo bcpow('3', '47');

echo gmp_strval( gmp_pow('3', '47') );

The PHP.net documentation has a nice section about that topic:

Floating point precision

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

For a "simple" explanation, see the » floating point guide that's also titled "Why don’t my numbers add up?"
http://php.net/manual/en/language.types.float.php

Note that the php.ini configuration value 'precision' can also modify the precision when converting from floats to strings.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
1

bcpow() (a function of the BCMath Arbitrary Precision Mathematics library) can be used in this case.

echo bcpow('3', '47'); //as mentioned in ComFreek's answer
//outputs 26588814358957503287787 

The reason why pow isn't work here is because pow() uses float, and there's a size limitation for float.

See this excerpt from the PHP Manual:

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)

In other words, the maximum possible size may vary -- i.e. (may be different for 32-bit, and 64-bit systems).

Hope that answers your question!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150