mirror of
https://github.com/RustPython/RustPython.git
synced 2026-06-09 22:49:57 +09:00
Add complex.__abs__
This commit is contained in:
3
tests/snippets/builtin_complex.py
Normal file
3
tests/snippets/builtin_complex.py
Normal file
@@ -0,0 +1,3 @@
|
||||
assert complex(3, 4).__abs__() == 5
|
||||
assert complex(3, -4).__abs__() == 5
|
||||
assert complex(1.5, 2.5).__abs__() == 2.9154759474226504
|
||||
@@ -13,6 +13,7 @@ pub fn init(context: &PyContext) {
|
||||
"Create a complex number from a real part and an optional imaginary part.\n\n\
|
||||
This is equivalent to (real + imag*1j) where imag defaults to 0.";
|
||||
|
||||
context.set_attr(&complex_type, "__abs__", context.new_rustfunc(complex_abs));
|
||||
context.set_attr(&complex_type, "__add__", context.new_rustfunc(complex_add));
|
||||
context.set_attr(&complex_type, "__new__", context.new_rustfunc(complex_new));
|
||||
context.set_attr(
|
||||
@@ -70,6 +71,13 @@ fn complex_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
|
||||
))
|
||||
}
|
||||
|
||||
fn complex_abs(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
|
||||
arg_check!(vm, args, required = [(zelf, Some(vm.ctx.complex_type()))]);
|
||||
|
||||
let Complex64 { re, im } = get_value(zelf);
|
||||
Ok(vm.ctx.new_float(re.hypot(im)))
|
||||
}
|
||||
|
||||
fn complex_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
|
||||
arg_check!(
|
||||
vm,
|
||||
|
||||
Reference in New Issue
Block a user