php-decimal / ext-decimal

Correctly-rounded, arbitrary precision decimal floating-point arithmetic in PHP
https://php-decimal.github.io/
MIT License
338 stars 19 forks source link

Factorial function? #50

Open joeyhub opened 4 years ago

joeyhub commented 4 years ago

For the sake of performance it would be great to have a factorial function in the library. It's in the documentation but as a PHP implementation.

I use gmp for it at the moment. I'm not sure if it's linear or not but either way C will be much faster for very large numbers.

On another note, this library is able to compute pow much faster than bcmath for very large exponents. This library can calculate something that ends up at E-500000 very quickly but bcmath takes prohibitively long.

I would recommend it to people having problems with bcmath and bcpow.

Another thing that bothers me is why so many of this libraries don't support initialisation from native php float which is a bit mind boggling. I have to use number_format($n, 72, '.', '').

joeyhub commented 4 years ago

It would also be very useful to have a documented way of formally suppressing the precision loss error and perhaps instead formally being able to check for it and taking the action of choice.

rtheunissen commented 4 years ago

Another thing that bothers me is why so many of this libraries don't support initialisation from native php float which is a bit mind boggling.

I think that these libraries opt to not be responsible for how to treat floating point values, instead leaving that up to the user or language itself. For example, casting a float to a string in PHP itself (string) $f is likely more consistent and predictable based on the language's configuration, eg .ini precision.

In saying that, it does introduce the potential for non-deterministic behavior. I'll take a look at introducing a format "from float" mechanism in 2.0 which I'm working on a stable release for, hopefully today.

rtheunissen commented 4 years ago

It would also be very useful to have a documented way of formally suppressing the precision loss error and perhaps instead formally being able to check for it and taking the action of choice.

I'll take a look at this too. :+1:

rtheunissen commented 4 years ago

For the sake of performance it would be great to have a factorial function in the library. It's in the documentation but as a PHP implementation.

mpdecimal does not have a factorial function built in but we can definitely support a formal version of it that calculates it using basic iterative multiplication. Adding to the list. :+1: