From 385f47c0cd7f4618640eee84124acdeea51cbb5a Mon Sep 17 00:00:00 2001 From: Koustav Chowdhury Date: Wed, 10 Jul 2019 00:42:52 +0530 Subject: [PATCH] add abs for complex, add tests (#1043) --- vlib/math/complex.v | 5 +++++ vlib/math/complex_test.v | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/vlib/math/complex.v b/vlib/math/complex.v index d98172dcff..d303e6f6d9 100644 --- a/vlib/math/complex.v +++ b/vlib/math/complex.v @@ -26,6 +26,11 @@ pub fn (c Complex) str() string { return out } +// Complex Absolute value +pub fn (c Complex) abs() f64 { + return C.hypot(c.re,c.im) +} + // Complex Angle pub fn (c Complex) angle() f64 { return atan2(c.im, c.re) diff --git a/vlib/math/complex_test.v b/vlib/math/complex_test.v index 0e9b5dafea..3d3be67610 100644 --- a/vlib/math/complex_test.v +++ b/vlib/math/complex_test.v @@ -103,6 +103,16 @@ fn test_complex_equals() { assert c1.equals(c2) } +fn test_complex_abs() { + mut c1 := math.complex(3,4) + assert c1.abs() == 5 + c1 = math.complex(1,2) + assert c1.abs() == math.sqrt(5) + assert c1.abs() == c1.conjugate().abs() + c1 = math.complex(7,0) + assert c1.abs() == 7 +} + fn test_complex_angle(){ mut c := math.complex(1, 0) assert c.angle() * 180 / math.Pi == 0