Skip to content

Commit

Permalink
Fix behavior of Math.sqrt at 0 (#9818) (#9828)
Browse files Browse the repository at this point in the history
* Fix behavior of Math.sqrt at 0 (#9818)

CHANGELOG_BEGIN
[Daml Compiler] Ensure that sqrt(0.0) == 0 and 0 ** 0 == 1
CHANGELOG_END
  • Loading branch information
rgugliel-da authored May 31, 2021
1 parent 7855ea5 commit 6af6c93
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
13 changes: 10 additions & 3 deletions compiler/damlc/daml-stdlib-src/DA/Math.daml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ infixr 8 **

-- | Take a power of a number Example: `2.0 ** 3.0 == 8.0`.
(**) : Decimal -> Decimal -> Decimal
x ** y = exp (y * log x)
x ** y
| y == 0.0 = 1.0
| x == 0.0 = 0.0
| otherwise = exp (y * log x)

-- | Calculate the square root of a Decimal.
--
Expand All @@ -34,7 +37,9 @@ x ** y = exp (y * log x)
-- 1.2
-- ```
sqrt : Decimal -> Decimal
sqrt x = x ** 0.5
sqrt x
| x < 0.0 = error "sqrt is defined only for non-negative numbers"
| otherwise = x ** 0.5

-- | The exponential function. Example: `exp 0.0 == 1.0`
exp : Decimal -> Decimal
Expand All @@ -47,7 +52,9 @@ exp x

-- | The natural logarithm. Example: `log 10.0 == 2.30258509299`
log : Decimal -> Decimal
log x = logt10k x / 10000.0
log x
| x <= 0.0 = error "logarithm is defined only for positive numbers"
| otherwise = logt10k x / 10000.0

-- | The logarithm of a number to a given base. Example: `log 10.0 100.0 == 2.0`
logBase : Decimal -> Decimal -> Decimal
Expand Down
11 changes: 10 additions & 1 deletion compiler/damlc/tests/daml-test-files/Math.daml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
-- All rights reserved.

-- @INFO range=47:22-47:32; Use sqrt
-- @INFO range=57:15-57:25; Use sqrt
-- @INFO range=66:15-66:25; Use sqrt


module Math where
Expand Down Expand Up @@ -45,6 +45,15 @@ powerTest = scenario do
let
sqrt2 = 1.4142135623 : Decimal
assert(abs(sqrt2 - 2.0 ** 0.5) <= 0.0000000001)
0.0 ** 0.0 === 1.0
0.0 ** 1.0 === 0.0
42.0 ** 0.0 === 1.0

sqrtTest = scenario do
let
sqrt2 = 1.4142135623 : Decimal
assert(abs(sqrt2 - sqrt 2.0) <= 0.0000000001)
sqrt 0.0 === 0.0

trigTest = scenario do
let
Expand Down

0 comments on commit 6af6c93

Please sign in to comment.