Assess numerical stability
Assess numerical stability
Floating-point calculations round intermediate results. Algebraically equivalent expressions may behave differently because of overflow, underflow or cancellation (loss of significant digits when nearly equal numbers are subtracted). Prefer library algorithms designed to avoid those hazards, and test the intended input range.
package main
import ( "fmt" "math")
func main() { x := 1e200 fmt.Println(math.IsInf(math.Sqrt(x*x+x*x), 0)) fmt.Println(!math.IsInf(math.Hypot(x, x), 0))}Squaring x overflows float64 even though the final mathematical norm fits. Hypot avoids unnecessary intermediate overflow and underflow. The second assertion checks finiteness, not exact equality to the mathematical result.
Expected output:
truetrueCompare near zero carefully
package main
import ( "fmt" "math")
func main() { x := 1e-20 fmt.Println(math.Exp(x)-1 == 0) fmt.Println(math.Expm1(x) > 0)}Exp(x) rounds to one for this small x, so subtraction loses the increment. Expm1 computes exp(x)-1 more accurately near zero. For approximate comparisons choose tolerances based on problem scale; a fixed epsilon is not universal, and NaN must be handled explicitly.
Expected output:
truetrueTry it locally
For x=1e-20, print whether math.Log(1+x) is zero and math.Log1p(x) is positive.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Numeric engineering 08: Assess numerical stability
Check the lesson objective before moving on.
Why can sqrt(x*x+y*y) overflow unnecessarily?
Which is designed for exp(x)-1 near zero?