Skip to content

Commit

Permalink
Call simplify before toFloat conversion (#73)
Browse files Browse the repository at this point in the history
  • Loading branch information
olsavmic authored Aug 10, 2022
1 parent de84657 commit d54a395
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/BigRational.php
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,8 @@ public function toInt() : int
*/
public function toFloat() : float
{
return $this->numerator->toFloat() / $this->denominator->toFloat();
$simplified = $this->simplified();
return $simplified->numerator->toFloat() / $simplified->denominator->toFloat();
}

/**
Expand Down
32 changes: 32 additions & 0 deletions tests/BigRationalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -892,6 +892,38 @@ public function providerToIntThrowsException() : array
];
}

public function testIdentityOperationResultsInDifferentToFloatValueWithoutSimplification() : void
{
$expectedValue = 11.46;
$conversionFactor = BigRational::of('0.45359237');
$value = BigRational::of($expectedValue);

$identicalValueAfterMathOperations = $value->multipliedBy($conversionFactor)
->dividedBy($conversionFactor)
->multipliedBy($conversionFactor)
->dividedBy($conversionFactor)
->multipliedBy($conversionFactor)
->dividedBy($conversionFactor);

self::assertSame($expectedValue, $identicalValueAfterMathOperations->toFloat());

// Assert that simplification is required and the test would fail without it
self::assertNotSame(
$expectedValue,
$identicalValueAfterMathOperations->getNumerator()->toFloat() / $identicalValueAfterMathOperations->getDenominator()->toFloat(),
);
}

public function testToFloatConversionPerformsSimplificationToPreventOverflow() : void
{
$int = BigInteger::of('1e4000');
$val = BigRational::nd($int, $int);

self::assertInfinite($val->getNumerator()->toFloat());
// Assert that simplification is required and the test would fail without it
self::assertSame(1.0, $val->toFloat());
}

/**
* @dataProvider providerToFloat
*
Expand Down

0 comments on commit d54a395

Please sign in to comment.