实现说明
这个示例的骨架由 StrictMathDemo和函数 main构成。
使用要点
- 跑完文件,输出里会留下标记——
sin:、pow:、expm1:。
常见问题
运行「StrictMath 逐位可复现函数」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 sin:、pow:、expm1: 标签标明各步骤。
核心语句
double hyp = StrictMath.hypot(1.0e300, 1.0e300);
double p = StrictMath.pow(2.0, 10.0);
double e = StrictMath.expm1(0.01);
代码示例
public class StrictMathDemo {
public static void main(String[] args) {
// StrictMath:fdlibm 5.3 算法的 Java 转写,任何平台逐位一致
double s = StrictMath.sin(0.5);
double c = StrictMath.cos(0.5);
double p = StrictMath.pow(2.0, 10.0);
double e = StrictMath.expm1(0.01);
System.out.println("sin: " + s);
System.out.println("pow: " + p);
System.out.println("expm1:" + e);
// Math:默认多数方法直接委托 StrictMath,但允许平台用更快实现,
// 不保证逐位一致;常见场景下两者给出同一个值
double ms = Math.sin(0.5);
System.out.println("Math.sin same as StrictMath.sin: " + (ms == s));
// hypot 避免中间溢出:两条直角边各取极大值仍能得到正确斜边
double hyp = StrictMath.hypot(1.0e300, 1.0e300);
System.out.println("hypot: " + hyp);
// 基本运算(+ - * /)两版没有差别:差异只来自超越函数
System.out.println("arithmetic identical: " + (0.1 + 0.2 == StrictMath.abs(-0.30000000000000004)));
}
}