1

The parameter for index 5 needs to be 0 in below code.

But The value for echo($a[5]) comes 1.2325951644078E-32.

The loop prints correct values for all other parameters except for 5th index (which needs to be 0 according to me).

Can anybody tell me why is that happening??

for($x=-2;$x<2.1;$x+=0.4){

     $a[] = $x*$x;
 }

echo($a[5]); //this is not printing 0 why?

Output is:-

Array
(
    [0] => 4
    [1] => 2.56
    [2] => 1.44
    [3] => 0.64
    [4] => 0.16
    [5] => 1.2325951644078E-32
    [6] => 0.16
    [7] => 0.64
    [8] => 1.44
    [9] => 2.56
    [10] => 4
)
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
dev740
  • 111
  • 2
  • 6
  • I'm asking about index 5 – dev740 Oct 18 '19 at 04:48
  • Be careful with floating point math, see this: https://3v4l.org/64b4f You can see it show the same result, it is because the way floating point is stored in the memory. Check this: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – catcon Oct 18 '19 at 05:01
  • So what can be done to avoid this ? – dev740 Oct 18 '19 at 05:13

2 Answers2

1

it should be zero.. Modify your code like this and try..

 $a[] = number_format($x*$x,2);
josephthomaa
  • 158
  • 1
  • 11
1

Bro you forget to convert to number format before math.

for($x=-2;$x<2.1;$x+=0.4){

     $a[] = number_format($x)*number_format($x);
 }

echo($a[5]); // 0

Hope help this.

  • I got it by changing number_format($x)*number_format($x); to number_format($x,2)*number_format($x,2); – dev740 Oct 18 '19 at 05:21