From 8137798937104b90b2d685d5d5b8fb5cffae4c9f Mon Sep 17 00:00:00 2001 From: bdeket Date: Fri, 30 Oct 2020 17:36:13 +0100 Subject: [PATCH] Improve (sinh x) : x around 0 (#3473) * sinh - Taylor expansion near 0 * fast path for |z| < 1e-8 in this case the second term is already to small to matter --- pkgs/racket-test-core/tests/racket/math.rktl | 4 ++-- racket/collects/racket/math.rkt | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/pkgs/racket-test-core/tests/racket/math.rktl b/pkgs/racket-test-core/tests/racket/math.rktl index 85e1bf459e..b196ac02f3 100644 --- a/pkgs/racket-test-core/tests/racket/math.rktl +++ b/pkgs/racket-test-core/tests/racket/math.rktl @@ -279,10 +279,10 @@ (test -inf.0 sinh -inf.0) (test -inf.0 sinh -max.0) (test #t double=? sinh-1 (sinh -1.0)) -(test -0.0 sinh -min.0) +(test -min.0 sinh -min.0) (test -0.0 sinh -0.0) (test 0.0 sinh 0.0) -(test 0.0 sinh +min.0) +(test +min.0 sinh +min.0) (test #t double=? sinh+1 (sinh 1.0)) (test +inf.0 sinh +max.0) (test +inf.0 sinh +inf.0) diff --git a/racket/collects/racket/math.rkt b/racket/collects/racket/math.rkt index 50a0919ddc..12bfe5b8cd 100644 --- a/racket/collects/racket/math.rkt +++ b/racket/collects/racket/math.rkt @@ -58,6 +58,12 @@ [(real? z) (let loop ([z z]) (cond [(z . < . 0) (- (loop (- z)))] + [(< z 1e-8) (exact->inexact z)] + [(< z .13) + ;; Taylor expansion near 0 to avoid cancellation + ;~ z+z^3/3!+z^5/5!+... + (define z^2 (* z z)) + (+ z (* z z^2 (+ #i1/6 (* z^2 (+ #i1/120 (* z^2 (+ #i1/5040 (* z^2 #i1/362880))))))))] [else (/ (- (exp z) (exp (- z))) 2)]))] [else (/ (- (exp z) (exp (- z))) 2)]))