java中的数学计算Math类

java中的数学计算Math类

在高效学习技巧中,固定类的知识是需要死记硬背的。实践类的知识需要实践才能理解其道理。方法类的知识需要了解大概,用到的时候再祥查即可。

Math类就属于方法类知识,虽然在实际项目中很少用到,但是总会用到。所以当你遇到相关问题的时候能够马上能想到它。

例如:项目中需要对一组数据进行四舍五入那么可以马上想到 Math.round(double a)

那在Java中Math类是干嘛的?

Math类在java.lang包中,包含完成基本数学函数所需的方法。

Math类的方法太多有方便记忆的办法吗?

在Math类中有两个静态double型常量E(自然对数)和PI(圆周率)。

//自然对数的底数
public static final double E = 2.7182818284590452354;
//圆的周长与直径之比
public static final double PI = 3.14159265358979323846;

为了方便记忆将Math类方法概括如下


  • 取整方法

//返回最小的(最接近负无穷大)double 值 例如传1.2返回2.0  
static double ceil(double a);
//返回最大的(最接近正无穷大)double 值 例如传1.2返回1.0  
static double floor(double a);
//四舍五入,返回double值
static double rint(double a);
//四舍五入,返回long值
static long round(double a);
//四舍五入,返回int值
static int round(float a);
  • 三角函数方法

/**
 * 将用弧度表示的角转换为近似相等的用角度表示的角
 * 将-π/2到π/2之间的弧度值转化为度 例如:Math.toDegrees(Math.PI/2)结果为90.0;
static double toDegrees(double angrad);
 * 将用角度表示的角转换为近似相等的用弧度表示的角
 * 将度转化为-π/2到π/2之间的弧度值 例如:Math.toRadians(30)结果为 π/6;
static double toRadians(double angdeg);
 * Math.sin、Math.cos、Math.tan这三个方法是三角函数中的正弦、余弦和正切
 * 反之Math.asin、Math.acos、Math.atan是他们的反函数
static double sin(double a);
static double cos(double a);
static double tan(double a); 
static double asin(double a);
static double acos(double a);
static double atan(double a);
  • 指数函数

//获得以e为底a为指数的数值
static double expdouble a;  
//对数函数
static double log(double a);
//底数为 10 的对数
static double log10(double a); 
//a为底b为指数的值
static double pow(double a, double b); 
//正平方根
static double sqrt(double a);
  • 最大值和最小值以及绝对值

//最大值
static double max(double a, double b);
static float max(float a, float b); 
static int max(int a, int b); 
static long max(long a, long b);
//最小值
static double min(double a, double b);
static float min(float a, float b);
static int min(int a, int b);
static long min(long a, long b);
//绝对值
static double abs(double a);