Math Sqrt Pow Log And Exp Functions

Compute square roots, powers, and logarithms with math.Sqrt, math.Pow, math.Log2, and math.Exp, and confirm invalid inputs propagate as NaN.

GoData Integrity

Code

gosnippet
25 lines
package main

import (
	"fmt"
	"math"
)

func main() {
	side := 13.0
	fmt.Printf("sqrt(%v) = %v\n", side, math.Sqrt(side))

	base, exp := 2.0, 10.0
	fmt.Printf("pow(%v, %v) = %v\n", base, exp, math.Pow(base, exp))

	// 信息论里常用以 2 为底的对数
	fmt.Printf("log2(1024) = %v\n", math.Log2(1024))
	fmt.Printf("log(64) natural = %.4f\n", math.Log(64))

	// 连续复利:exp 直接按增长率放大
	rate, years := 0.07, 10.0
	fmt.Printf("exp(0.07*10) = %.4f\n", math.Exp(rate*years))

	// 非法输入传播为 NaN,而不是 panic
	fmt.Printf("sqrt(-4).isNaN = %v\n", math.IsNaN(math.Sqrt(-4)))
}

What the file does

Structurally, expect the function main and nothing else.

Caveats

  • All standard library — copy it in and it just runs.

Putting it to use

Entry signature: func main()

The demo output is labeled (sqrt(, pow(, log2(1024) =), so the output can be traced line by line to the code that printed it.

Lines that do the work

rate, years := 0.07, 10.0

Interactive Tools for This Topic

FAQ

What does Math Sqrt Pow Log And Exp Functions print when run?
Invoke the file as-is — the `sqrt(`, `pow(`, `log2(1024) =` prefixes identify which step printed each line.