views:

60

answers:

2

This is the weirdest thing that has ever happened to me sime I am a (PHP) programmer...

I have two files, with the following code (proj. euler stuff) that return different outputs.

<?php
$numbers =<<<eot
2,3
5,2
9,3
4,9
6,3
10,5
eot;
$numbers = explode("\n",$numbers);
$max = 0;
foreach($numbers as $k => $n){
    list($base,$expo) = explode(',',$n);
    $theLog = log($base,10);
    $result = bcmul($theLog,$expo,10);

    if(bccomp($result,$max,10) == 1){
        echo '<br/>max so far is ' . $result . ' for base ' . $base . '[log:'.$theLog.'] and exponent ' . $expo ;
        $max = $result;
    }
}
echo '<pre>';
print_r($numbers);
echo '</pre>';
echo $max;

FILE1, euler.php // outputs as expected:

max so far is 0.9030899869 for base 2[log:0.30102999566398] and exponent 3
max so far is 1.3979400086 for base 5[log:0.69897000433602] and exponent 2
max so far is 2.8627275283 for base 9[log:0.95424250943932] and exponent 3
max so far is 5.4185399219 for base 4[log:0.60205999132796] and exponent 9

5.4185399219

FILE2, euler2.php // bogus output:

max so far is 5 for base 10[log:1] and exponent 5

5

Can anyone think of a valid reason for this to happen?

I've tested it and I can tell that in euler2.php, the bogus one, $result = bcmul($theLog,$expo,10); doesn't like $theLog being a float value, therefore bcmul(0,$expo) = 0. $theLog, however, holds the right value.

Why would bc functions behaviour change from one file to the other?

NOTE: There is no bcscale set in any of the files, and if I set it to bcscale(10); the result is exactly the same.

+3  A: 

You have different EOL characters in your files. I can repro your error with Windows EOL (\r\n) and correct behaviour with Unix EOL (\n).

SilentGhost
that's exactly the issue... one file has `\r` while other has `\n`... I don't know why though, same editor being used for both files and code was copy pasted from the one working to the other...
acmatos
+2  A: 

Sometimes when files look identical, they can have different encodings or line-endings.

Can't say why that would affect your result though.

Try diffing them (eg. using WinMerge)

Using Notepad++ you can easily edit the encoding and/or line-endings, via the Format menu.

gt
I was using notepad++ and copy/pasted code from one file to the other however, that's the issue... EOL are different therefore `explode("\n")` will work in first file while `explode("\r")` will work in second file... thanks :)
acmatos