Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
* fix nim-lang#16494

* fix

* fix

* fix

* fix

* fix

* fix performance

* add comments

* improve performance

* Update lib/system.nim

Co-authored-by: Timothee Cour <[email protected]>

* Update lib/system.nim

Co-authored-by: Timothee Cour <[email protected]>

* Update tests/stdlib/tmath_misc.nim

Co-authored-by: Timothee Cour <[email protected]>

* Update tests/stdlib/tmath_misc.nim

Co-authored-by: Timothee Cour <[email protected]>

Co-authored-by: Timothee Cour <[email protected]>
  • Loading branch information
ringabout and timotheecour authored Jan 1, 2021
1 parent 5fb56a3 commit 9d4a1f9
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
24 changes: 20 additions & 4 deletions lib/system.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1522,10 +1522,26 @@ include "system/iterators_1"

{.push stackTrace: off.}

proc abs*(x: float64): float64 {.noSideEffect, inline.} =
if x < 0.0: -x else: x
proc abs*(x: float32): float32 {.noSideEffect, inline.} =
if x < 0.0: -x else: x

when defined(js):
proc js_abs[T: SomeNumber](x: T): T {.importc: "Math.abs".}
else:
proc c_fabs(x: cdouble): cdouble {.importc: "fabs", header: "<math.h>".}
proc c_fabsf(x: cfloat): cfloat {.importc: "fabsf", header: "<math.h>".}

proc abs*[T: float64 | float32](x: T): T {.noSideEffect, inline.} =
when nimvm:
if x < 0.0: result = -x
elif x == 0.0: result = 0.0 # handle 0.0, -0.0
else: result = x # handle NaN, > 0
else:
when defined(js): result = js_abs(x)
else:
when T is float64:
result = c_fabs(x)
else:
result = c_fabsf(x)

proc min*(x, y: float32): float32 {.noSideEffect, inline.} =
if x <= y or y != y: x else: y
proc min*(x, y: float64): float64 {.noSideEffect, inline.} =
Expand Down
24 changes: 24 additions & 0 deletions tests/stdlib/tmath_misc.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
discard """
targets: "c js"
"""

# TODO merge this to tmath.nim once tmath.nim supports js target

import math

proc main() =
block:
doAssert 1.0 / abs(-0.0) == Inf
doAssert 1.0 / abs(0.0) == Inf
doAssert -1.0 / abs(-0.0) == -Inf
doAssert -1.0 / abs(0.0) == -Inf
doAssert abs(0.0) == 0.0
doAssert abs(0.0'f32) == 0.0'f32

doAssert abs(Inf) == Inf
doAssert abs(-Inf) == Inf
doAssert abs(NaN).isNaN
doAssert abs(-NaN).isNaN

static: main()
main()

0 comments on commit 9d4a1f9

Please sign in to comment.