Skip to content

Commit bd696b5

Browse files
authored
Merge pull request RustPython#4199 from jopemachine/fix-harmonic_mean
Fix `int.inner_truediv`
2 parents 46ff239 + 773066f commit bd696b5

File tree

2 files changed

+11
-27
lines changed

2 files changed

+11
-27
lines changed

Lib/test/test_statistics.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -691,8 +691,6 @@ def test_check_all(self):
691691
'missing name "%s" in __all__' % name)
692692

693693

694-
# TODO: RUSTPYTHON
695-
@unittest.expectedFailure
696694
class DocTests(unittest.TestCase):
697695
@unittest.skipIf(sys.flags.optimize >= 2,
698696
"Docstrings are omitted with -OO and above")

vm/src/builtins/int.rs

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,9 @@ use crate::{
1818
use bstr::ByteSlice;
1919
use num_bigint::{BigInt, BigUint, Sign};
2020
use num_integer::Integer;
21+
use num_rational::Ratio;
2122
use num_traits::{One, Pow, PrimInt, Signed, ToPrimitive, Zero};
22-
use std::ops::Neg;
23+
use std::ops::{Div, Neg};
2324
use std::{fmt, ops::Not};
2425

2526
/// int(x=0) -> integer
@@ -212,31 +213,16 @@ fn inner_truediv(i1: &BigInt, i2: &BigInt, vm: &VirtualMachine) -> PyResult {
212213
return Err(vm.new_zero_division_error("division by zero".to_owned()));
213214
}
214215

215-
let value = if let (Some(f1), Some(f2)) = (i2f(i1), i2f(i2)) {
216-
f1 / f2
217-
} else {
218-
let (quotient, mut rem) = i1.div_rem(i2);
219-
let mut divisor = i2.clone();
220-
221-
if let Some(quotient) = i2f(&quotient) {
222-
let rem_part = loop {
223-
if rem.is_zero() {
224-
break 0.0;
225-
} else if let (Some(rem), Some(divisor)) = (i2f(&rem), i2f(&divisor)) {
226-
break rem / divisor;
227-
} else {
228-
// try with smaller numbers
229-
rem /= 2;
230-
divisor /= 2;
231-
}
232-
};
216+
let float = Ratio::from(i1.clone()).div(i2).to_f64().unwrap();
233217

234-
quotient + rem_part
235-
} else {
236-
return Err(vm.new_overflow_error("int too large to convert to float".to_owned()));
237-
}
238-
};
239-
Ok(vm.ctx.new_float(value).into())
218+
if float.is_infinite() {
219+
Err(vm.new_exception_msg(
220+
vm.ctx.exceptions.overflow_error.to_owned(),
221+
"integer division result too large for a float".to_owned(),
222+
))
223+
} else {
224+
Ok(vm.ctx.new_float(float).into())
225+
}
240226
}
241227

242228
impl Constructor for PyInt {

0 commit comments

Comments
 (0)