Skip to content

Commit

Permalink
Add Complex version of almostEqual function (#23549)
Browse files Browse the repository at this point in the history
This adds a version of `almostEqual` (which was already available for
floats) thata works with `Complex[SomeFloat]`.

Proof that this is needed is that the first thing that the complex.nim
runnable examples block did before this commit was define (an
incomplete) `almostEqual` function that worked with complex values.
  • Loading branch information
AngelEzquerra committed May 8, 2024
1 parent 09bd9d0 commit d8e1504
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/pure/complex.nim
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@
runnableExamples:
from std/math import almostEqual, sqrt

func almostEqual(a, b: Complex): bool =
almostEqual(a.re, b.re) and almostEqual(a.im, b.im)

let
z1 = complex(1.0, 2.0)
z2 = complex(3.0, -4.0)
Expand Down Expand Up @@ -412,6 +409,24 @@ func rect*[T](r, phi: T): Complex[T] =
## * `polar func<#polar,Complex[T]>`_ for the inverse operation
complex(r * cos(phi), r * sin(phi))

func almostEqual*[T: SomeFloat](x, y: Complex[T]; unitsInLastPlace: Natural = 4): bool =
## Checks if two complex values are almost equal, using the
## [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon).
##
## Two complex values are considered almost equal if their real and imaginary
## components are almost equal.
##
## `unitsInLastPlace` is the max number of
## [units in the last place](https://en.wikipedia.org/wiki/Unit_in_the_last_place)
## difference tolerated when comparing two numbers. The larger the value, the
## more error is allowed. A `0` value means that two numbers must be exactly the
## same to be considered equal.
##
## The machine epsilon has to be scaled to the magnitude of the values used
## and multiplied by the desired precision in ULPs unless the difference is
## subnormal.
almostEqual(x.re, y.re, unitsInLastPlace = unitsInLastPlace) and
almostEqual(x.im, y.im, unitsInLastPlace = unitsInLastPlace)

func `$`*(z: Complex): string =
## Returns `z`'s string representation as `"(re, im)"`.
Expand Down
3 changes: 3 additions & 0 deletions tests/stdlib/tcomplex.nim
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ let t = polar(a)
doAssert(rect(t.r, t.phi) =~ a)
doAssert(rect(1.0, 2.0) =~ complex(-0.4161468365471424, 0.9092974268256817))

doAssert(almostEqual(a, a + complex(1e-16, 1e-16)))
doAssert(almostEqual(a, a + complex(2e-15, 2e-15), unitsInLastPlace = 5))


let
i64: Complex32 = complex(0.0f, 1.0f)
Expand Down

0 comments on commit d8e1504

Please sign in to comment.