← 中文资源

简体中文版本

math 的 Sqrt/Pow/Log/Exp 函数

用 math.Sqrt/math.Pow/math.Log2/math.Exp 做平方根、幂与对数运算;非法输入如负数开方不会 panic,而是返回 NaN,用 math.IsNaN 检出。

阅读英文原文

实现说明

math 的 Sqrt/Pow/Log/Exp 函数的核心是函数 main。

使用要点

  • 直接运行文件,输出会带上标签,比如 sqrt(、pow(、log2(1024) =——输出的每一行都能指回产生它的那次调用。

常见问题

运行「math 的 Sqrt/Pow/Log/Exp 函数」会打印什么?

整个文件跑完,输出行以 sqrt(、pow(、log2(1024) = 这类前缀开头。

核心语句

rate, years := 0.07, 10.0

代码示例

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)))
}