hoaproject/Math

Strange bug with #negative

jubianchi opened this issue · 9 comments

Here is the expression I use : $expr = '2 + 2 / 2560.4 + - 2';

With PHP, I get:

<?php

var_dump((float) eval('return ' . $expr . ';')); // float(0.00078112794875818)

With Math, I get:

<?php
use Hoa\Compiler;
use Hoa\File;
use Hoa\Math\Visitor\Arithmetic;

$compiler = Compiler\Llk\Llk::load(new File\Read('hoa://Library/Math/Arithmetic.pp'));
$visitor  = new Arithmetic();
$dump = new Compiler\Visitor\Dump();

$ast = $compiler->parse($expr);

echo $dump->visit($ast);
var_dump((float) $visitor->visit($ast)); // float(0.00078112794875795)

Here is the produced AST:

>  #addition
>  >  token(number, 2)
>  >  #addition
>  >  >  #division
>  >  >  >  token(number, 2)
>  >  >  >  token(number, 2560.4)
>  >  >  #negative
>  >  >  >  token(number, 2)

Changing the expression to:

  • 2 + 2 / 2560.4 - 2 makes both results identical,
  • 2 + 2 / 2560.4 + - 3 makes both results identical,
  • 2 + 2 / 2560.3 + - 2 makes both results identical,
  • 2 + 2 / 2560.4 + - - 2 makes both results identical,
  • 2 + 2 / 2560.4 + - + 2 makes results different,
  • ...

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Hywan commented

OK… So, the AST is correct. Can you find a Minimal Working Example?

Hywan commented

I cannot reproduce.

Hywan commented

ping?

Hywan commented

Oh, finally I can reproduce!

Hywan commented

Explanations

For Hoa, 2 + (2 / 2560.4) + -2 is considered as 2 + ( (2 / 2560.4) + -2 ).
For PHP, 2 + (2 / 2560.4) + -2 is considered as ( 2 + (2 / 2560.4) ) + -2, because + -2 is resolved to -2 directly. Then, let's try this simplification directly:

2 + (2 / 2560.4) - 2 is equal to 0.00078112794875818 both for Hoa and PHP.

Solution

Working on it.

Hywan commented

Should we fix it 🙄? cc @jubianchi @CircleCode

Hywan commented

A solution would be to traverse the whole expression, apply simplifications, and then evaluate it. Else, there will still be an edge case somewhere.

I think we should do our best to fix this issue. It will clarify both usages and contributions.

When I found this bug, I had a hard time figuring ou if I introduced this bug or if it was already here.

In a user point of view, having the exact same behavior than PHP would make things totally predictable.

Hywan commented

Agree. I don't have time right now to fix it though :-(.