diff --git a/vlib/builtin/int.v b/vlib/builtin/int.v index c1ba5b617d..989826bc11 100644 --- a/vlib/builtin/int.v +++ b/vlib/builtin/int.v @@ -4,6 +4,12 @@ module builtin +#include + +import const ( + DBL_EPSILON +) + pub fn (d double) str() string { buf := malloc(sizeof(double) * 5 + 1)// TODO C.sprintf(buf, '%f', d) @@ -28,6 +34,11 @@ pub fn ptr_str(ptr voidptr) string { return tos(buf, strlen(buf)) } +// compare floats using C epsilon +pub fn (a f64) eq(b f64) bool { + return C.fabs(a - b) <= DBL_EPSILON +} + // fn (nn i32) str() string { // return i // } diff --git a/vlib/math/complex_test.v b/vlib/math/complex_test.v index c42fcc4f96..bff6addc63 100644 --- a/vlib/math/complex_test.v +++ b/vlib/math/complex_test.v @@ -115,8 +115,8 @@ fn test_complex_abs() { mut c1 := cmplx.complex(3,4) assert c1.abs() == 5 c1 = cmplx.complex(1,2) - assert c1.abs() == math.sqrt(5) - assert c1.abs() == c1.conjugate().abs() + assert c1.abs().eq(math.sqrt(5)) + assert c1.abs().eq(c1.conjugate().abs()) c1 = cmplx.complex(7,0) assert c1.abs() == 7 } @@ -125,17 +125,17 @@ fn test_complex_angle(){ // Test is based on and verified from practice examples of Khan Academy // https://www.khanacademy.org/math/precalculus/imaginary-and-complex-numbers mut c := cmplx.complex(1, 0) - assert c.angle() * 180 / math.Pi == 0 + assert (c.angle() * 180 / math.Pi).eq(0) c = cmplx.complex(1, 1) - assert c.angle() * 180 / math.Pi == 45 + assert (c.angle() * 180 / math.Pi).eq(45) c = cmplx.complex(0, 1) - assert c.angle() * 180 / math.Pi == 90 + assert (c.angle() * 180 / math.Pi).eq(90) c = cmplx.complex(-1, 1) - assert c.angle() * 180 / math.Pi == 135 + assert (c.angle() * 180 / math.Pi).eq(135) c = cmplx.complex(-1, -1) - assert c.angle() * 180 / math.Pi == -135 + assert (c.angle() * 180 / math.Pi).eq(-135) mut cc := c.conjugate() - assert cc.angle() + c.angle() == 0 + assert (cc.angle() + c.angle()).eq(0) } diff --git a/vlib/math/math_test.v b/vlib/math/math_test.v index a7abd8124e..de45a0eda4 100644 --- a/vlib/math/math_test.v +++ b/vlib/math/math_test.v @@ -35,10 +35,10 @@ fn test_factorial() { fn test_erf() { assert math.erf(0) == 0 - assert math.erf(1.5) + math.erf(-1.5) == 0 + assert (math.erf(1.5) + math.erf(-1.5)).eq(0) assert math.erfc(0) == 1 - assert math.erf(2.5) + math.erfc(2.5) == 1 - assert math.erfc(3.6) + math.erfc(-3.6) == 2 + assert (math.erf(2.5) + math.erfc(2.5)).eq(1) + assert (math.erfc(3.6) + math.erfc(-3.6)).eq(2) } fn test_gamma() {