Fix pow overflow (#784)

This commit is contained in:
HarmoGlace 2023-04-13 21:08:54 +02:00 committed by GitHub
parent 6d596da72b
commit 29b36d4876
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 1 deletions

View File

@ -108,7 +108,11 @@ pub fn pow(
}; };
let result = match (base, exponent.v) { let result = match (base, exponent.v) {
(Num::Int(a), Num::Int(b)) if b >= 0 => Num::Int(a.pow(b as u32)), (Num::Int(a), Num::Int(b)) if b >= 0 => a
.checked_pow(b as u32)
.map(Num::Int)
.ok_or("the result is too large")
.at(args.span)?,
(a, Num::Int(b)) => Num::Float(a.float().powi(b as i32)), (a, Num::Int(b)) => Num::Float(a.float().powi(b as i32)),
(a, b) => Num::Float(a.float().powf(b.float())), (a, b) => Num::Float(a.float().powf(b.float())),
}; };

View File

@ -90,6 +90,10 @@
// Error: 14-31 exponent is too large // Error: 14-31 exponent is too large
#calc.pow(2, 10000000000000000) #calc.pow(2, 10000000000000000)
---
// Error: 10-25 the result is too large
#calc.pow(2, 2147483647)
--- ---
// Error: 14-36 exponent may not be infinite, subnormal, or NaN // Error: 14-36 exponent may not be infinite, subnormal, or NaN
#calc.pow(2, calc.pow(2.0, 10000.0)) #calc.pow(2, calc.pow(2.0, 10000.0))