mirror of
https://github.com/RustPython/RustPython.git
synced 2026-06-02 19:39:49 +09:00
Added the ability to do addition between complex numbers and ints.
This commit is contained in:
@@ -38,3 +38,7 @@ assert b.real == 0
|
||||
|
||||
assert a.imag == 4
|
||||
assert b.imag == 4
|
||||
|
||||
# int and complex addition
|
||||
assert 1 + 1j == complex(1, 1)
|
||||
assert 1j + 1 == complex(1, 1)
|
||||
|
||||
@@ -106,6 +106,8 @@ fn complex_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
|
||||
let v1 = get_value(i);
|
||||
if objtype::isinstance(i2, &vm.ctx.complex_type()) {
|
||||
Ok(vm.ctx.new_complex(v1 + get_value(i2)))
|
||||
} else if objtype::isinstance(i2, &vm.ctx.int_type()) {
|
||||
Ok(vm.ctx.new_complex(Complex64::new(v1.re + objint::get_value(i2).to_f64().unwrap(), v1.im)))
|
||||
} else {
|
||||
Err(vm.new_type_error(format!("Cannot add {} and {}", i.borrow(), i2.borrow())))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::objfloat;
|
||||
use super::objstr;
|
||||
use super::objtype;
|
||||
use super::objcomplex;
|
||||
use crate::format::FormatSpec;
|
||||
use crate::pyobject::{
|
||||
FromPyObjectRef, PyContext, PyFuncArgs, PyObject, PyObjectPayload, PyObjectRef, PyResult,
|
||||
@@ -10,6 +11,7 @@ use crate::vm::VirtualMachine;
|
||||
use num_bigint::{BigInt, ToBigInt};
|
||||
use num_integer::Integer;
|
||||
use num_traits::{Pow, Signed, ToPrimitive, Zero};
|
||||
use num_complex::Complex64;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
// This proxy allows for easy switching between types.
|
||||
@@ -289,6 +291,8 @@ fn int_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
|
||||
);
|
||||
if objtype::isinstance(other, &vm.ctx.int_type()) {
|
||||
Ok(vm.ctx.new_int(get_value(zelf) + get_value(other)))
|
||||
} else if objtype::isinstance(other, &vm.ctx.complex_type()) {
|
||||
Ok(vm.ctx.new_complex(Complex64::new(get_value(zelf).to_f64().unwrap() + objcomplex::get_value(other).re, objcomplex::get_value(other).im)))
|
||||
} else {
|
||||
Ok(vm.ctx.not_implemented())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user