浏览代码

* avoid overflow in tanh

florian 3 周之前
父节点
当前提交
74028317a7
共有 1 个文件被更改,包括 19 次插入15 次删除
  1. 19 15
      rtl/objpas/math.pp

+ 19 - 15
rtl/objpas/math.pp

@@ -1410,7 +1410,6 @@ function tanh(x : Single) : Single;
       if tmp=1 then
         exit(x);
 {$push}
-{$checkfpuexceptions on}
 {$safefpuexceptions on}
       result:=(tmp-1)/(1+tmp)
 {$pop}
@@ -1420,7 +1419,6 @@ function tanh(x : Single) : Single;
       if tmp=1 then
         exit(x);
 {$push}
-{$checkfpuexceptions on}
 {$safefpuexceptions on}
       result:=(1-tmp)/(1+tmp)
 {$pop}
@@ -1434,24 +1432,30 @@ function tanh(x : Double) : Double;
   var
     tmp:ValReal;
   begin
-    if x < 0 then begin
-      tmp:=exp(2*x);
-      if tmp=1 then
-        exit(x);
+    if abs(x)>20 then
+      begin
+        result:=sign(x);
+        exit;
+      end;
+
+    if x < 0 then
+      begin
+        tmp:=exp(2*x);
+        if tmp=1 then
+          exit(x);
 {$push}
-{$checkfpuexceptions on}
 {$safefpuexceptions on}
-      result:=(tmp-1)/(1+tmp)
+        result:=(tmp-1)/(1+tmp)
 {$pop}
-    end
-    else begin
-      tmp:=exp(-2*x);
-      if tmp=1 then
-        exit(x);
+      end
+    else
+      begin
+        tmp:=exp(-2*x);
+        if tmp=1 then
+          exit(x);
 {$push}
-{$checkfpuexceptions on}
 {$safefpuexceptions on}
-      result:=(1-tmp)/(1+tmp)
+        result:=(1-tmp)/(1+tmp)
 {$pop}
     end;
   end;