Java Math

Java 的 Math 包含了用于执行基本数学运算的属性和方法,如初等指数、对数、平方根和三角函数。

Math 的方法都被定义为 static 形式,通过 Math 类可以直接调用。

Math.PI

表示 π(圆周率)。

Math.E

表示 e(自然对数)。

随机数

Math.random() 生成一个0~1的随机数,类型为double,包括0但不包括1。

for(int i=0; i<3; i++){
    System.out.println(Math.random());
}

Math.random() 源码(Java7):

private static Random randomNumberGenerator;

private static synchronized Random initRNG() {
  Random rnd = randomNumberGenerator;
  return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd;
}

public static double random() {
  Random rnd = randomNumberGenerator;
  if (rnd == null) rnd = initRNG();
  return rnd.nextDouble();
}

random() 内部使用了一个 Random 类型的静态变量 randomNumberGenerator,实际是调用该变量的 nextDouble() 方法。

取最值

  • min / max
static int min(int x,int y)
  
static int max(int x,int y)

算术进位

  • ceil

Math.ceil() 返回大于或等于参数的最小整数 double 。

  • floor

Math.floor() 返回小于或等于参数的最大整数double`。

  • rint

Math.rint() 五舍六入取整,返回 double 值。

  • round

Math.round() 四舍五入取整,参数 double 时返回 long 值,float 时返回 int 值。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容