Skip to content

Commit 0117d4a

Browse files
committed
Make Big(Int|Float)::power() consistent with IEEE 754 rules
1 parent 84679e5 commit 0117d4a

File tree

4 files changed

+13
-5
lines changed

4 files changed

+13
-5
lines changed

src/main/php/math/BigFloat.class.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ public function divide($other) {
7878
* @return math.BigNum
7979
*/
8080
public function power($other) {
81+
if (0 === bccomp($this->num, 0) && -1 === bccomp($other instanceof self ? $other->num : $other, 0)) {
82+
throw new IllegalArgumentException('Negative power of zero');
83+
}
84+
8185
return new self(bcpow($this->num, $other instanceof self ? $other->num : $other));
8286
}
8387

src/main/php/math/BigInt.class.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,11 +169,15 @@ public function divide0($other) {
169169
/**
170170
* ^
171171
*
172-
* @see http://en.wikipedia.org/wiki/Exponentiation
172+
* @see http://en.wikipedia.org/wiki/Exponentiation
173173
* @param math.BigNum|int|float|string $other
174174
* @return math.BigNum
175175
*/
176176
public function power($other) {
177+
if (0 === bccomp($this->num, 0) && -1 === bccomp($other instanceof self ? $other->num : $other, 0)) {
178+
throw new IllegalArgumentException('Negative power of zero');
179+
}
180+
177181
if ($other instanceof self) {
178182
return new self(bcpow($this->num, $other->num));
179183
} else if (is_int($other)) {

src/test/php/math/unittest/BigFloatTest.class.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,9 @@ public function powerOfZeroZero() {
184184
Assert::equals(new BigFloat(1.0), (new BigFloat(0.0))->power(new BigFloat(0.0)));
185185
}
186186

187-
#[Test]
187+
#[Test, Expect(IllegalArgumentException::class)]
188188
public function powerOfZeroNegative() {
189-
Assert::equals(new BigFloat(0.0), (new BigFloat(0.0))->power(new BigFloat(-2)));
189+
(new BigFloat(0.0))->power(new BigFloat(-2));
190190
}
191191

192192
#[Test]

src/test/php/math/unittest/BigIntTest.class.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,9 +239,9 @@ public function powerOfZeroZero() {
239239
Assert::equals(new BigInt(1), (new BigInt(0))->power(new BigInt(0)));
240240
}
241241

242-
#[Test]
242+
#[Test, Expect(IllegalArgumentException::class)]
243243
public function powerOfZeroNegative() {
244-
Assert::equals(new BigInt(0), (new BigInt(0))->power(new BigInt(-2)));
244+
(new BigInt(0))->power(new BigInt(-2));
245245
}
246246

247247
#[Test]

0 commit comments

Comments
 (0)