I am having problems with the mathematical functions of php. I need to manipulate double precision numbers and I am using bcmath library. But when the number becomes smaller like 0.0001, I am not able to get the results for even addition.

Anybody knows what will be the problem? I set the scale to 30. Also, how can I display these numbers in scientific format like 1.0E-4 etc?

Thanks.

DrunkenHyena

08-06-2002, 05:49 PM

I've never used that library, so I can't help you with the first bit. Though I'd try setting the scale to roughly what you need it to be, 30 may not be supported. The docs are pretty skimpy on that library.

For the second bit, here's function to return a string formatted in scientific notation:

// float2exp converts floats into exponential notation

function float2exp($num) {

if (0 == $num) { return "0E1";}

list($int, $dec) = split("\.", $num);

// Extract sign

if ($int[0] == "+" || $int[0] == "-") {

$sign = substr($int, 0,1);

$int = substr($int, 1);

}

if (strlen($int) <= 1) { // abs($num) is less than 1

$i=0;

for ($i=0; $dec[$i]=='0' && $i < strlen($dec); $i++);

$exp = -$i-1;

$mantissa = substr($dec,$i,1).".".substr($dec,$i+1);

} else { // abs($num) is greater than 1

$i=0;

for ($i=0; $int[$i]=='0' && $i < strlen($int); $i++);

$exp = strlen($int)-1 - $i;

$mantissa = substr($int,$i,1).".".substr($int,$i+1).$dec;

}

return ($sign . $mantissa . "E" . $exp);

}

I didn't write it, I just got it off of www.php.net.

Thanks DrunkenHyena for you efforts.

I haven't completely resolved the problem. But there is lot more improvement now. Let me explain my application.

I've some data in a mysql database. The values that I'm using for calculation is of type double in the database. I retrieve the data using PHP and do some complex calcuations before presenting to the user.

Once I retrieve the data, I cast them into double as well. Precision setting in my PHP.INI is 14. In order to get this kind of precision, I used bcmath library to do the calculations. But, if the values are too small, output of my bcmath functions are 0.

Now, I set the precision of my PHP.INI to 5 and changed all the bcmath functions to normal calculations. I choose 5 as the data presentation is with the maximum of 5 decimal points. Now, I need not to do any formating for presenting the data, It looks fine.

Any way, I am still having problems with comparision of small numbers. Trying to resolve it now.