Commit 29ec011007 for golang

commit 29ec011007359056add816ea42798ba6534e77de
Author: Guido Iaquinti <guido.iaquinti@gmail.com>
Date:   Tue Dec 1 07:29:04 2026 +0000

    math: avoid premature overflow in Sinh and Cosh

    For large magnitudes, the Go implementations of Sinh and Cosh
    compute Exp(x)/2. At inputs such as 710, Exp(x) returns +Inf even
    though the halved exponential fits in a float64.

    When Exp(x) returns +Inf, compute Exp(x/2) and halve it before
    multiplying by Exp(x/2) again. Add test cases for both signs,
    including adjacent inputs on either side of the overflow boundary.

    Fixes #83480.

    Change-Id: I92fef7f47cd01b5975484adf9c42316350630349
    GitHub-Last-Rev: 9ef549a9de5be5e554fde08f68a07c96227eb66d
    GitHub-Pull-Request: golang/go#83481
    Reviewed-on: https://go-review.googlesource.com/c/go/+/868202
    Reviewed-by: Robert Griesemer <gri@google.com>
    Auto-Submit: Robert Griesemer <gri@google.com>
    Reviewed-by: Alan Donovan <adonovan@google.com>
    LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>

diff --git a/src/math/all_test.go b/src/math/all_test.go
index a679854159..143f00e10e 100644
--- a/src/math/all_test.go
+++ b/src/math/all_test.go
@@ -3150,6 +3150,27 @@ func TestSinh(t *testing.T) {
 	}
 }

+func TestSinhCoshOverflow(t *testing.T) {
+	for _, tt := range []struct {
+		x, want float64
+	}{
+		{709.5, 0x1.81e9b4b52d0c9p+1022},
+		{710, 0x1.3e21a464507f9p+1023},
+		// Adjacent float64 inputs on either side of overflow.
+		{0x1.633ce8fb9f87dp+9, 0x1.ffffffffffd3bp+1023},
+		{0x1.633ce8fb9f87ep+9, Inf(1)},
+	} {
+		for _, x := range []float64{tt.x, -tt.x} {
+			if got, want := Sinh(x), Copysign(tt.want, x); !close(got, want) {
+				t.Errorf("Sinh(%g) = %g, want %g", x, got, want)
+			}
+			if got := Cosh(x); !close(got, tt.want) {
+				t.Errorf("Cosh(%g) = %g, want %g", x, got, tt.want)
+			}
+		}
+	}
+}
+
 func TestSqrt(t *testing.T) {
 	for i := 0; i < len(vf); i++ {
 		a := Abs(vf[i])
diff --git a/src/math/sinh.go b/src/math/sinh.go
index 78b3c299d6..7674cb20ce 100644
--- a/src/math/sinh.go
+++ b/src/math/sinh.go
@@ -51,7 +51,7 @@ func sinh(x float64) float64 {
 	var temp float64
 	switch {
 	case x > 21:
-		temp = Exp(x) * 0.5
+		temp = expHalf(x)

 	case x > 0.5:
 		ex := Exp(x)
@@ -86,8 +86,19 @@ func Cosh(x float64) float64 {
 func cosh(x float64) float64 {
 	x = Abs(x)
 	if x > 21 {
-		return Exp(x) * 0.5
+		return expHalf(x)
 	}
 	ex := Exp(x)
 	return (ex + 1/ex) * 0.5
 }
+
+// expHalf computes exp(x)/2.
+func expHalf(x float64) float64 {
+	y := Exp(x)
+	if IsInf(y, 1) {
+		// use e^x == (e^(0.5*x))^2 to avoid exp(x) overflow
+		w := Exp(x * 0.5)
+		return w * 0.5 * w
+	}
+	return y * 0.5
+}