This article mainly shares with you the simple method of using Math in js, hoping to help everyone.
//Math是全局的 //Math.PI 数学里的3.1415926.... console.log(Math.PI); //取随机数 //js提供的随机函数 Math.random() -->[0,1)范围内的数 function random_int(start,end) { var num = start + (end - start) * Math.random(); //小数---》整数,向下取整 Math.floor() return Math.floor(num); } console.log(random_int(5,15)); console.log("======================="); //数学的正弦,余弦,正切 //单位是数学的弧度,而不是度,方向是数学的正方向,逆时针方向 console.log(Math.sin(Math.PI/4)); //sin 45° console.log(Math.sin(Math.PI/6)); //sin 45° console.log(Math.cos(Math.PI/6)); //cos 30° console.log(Math.tan(Math.PI/4)); //tan 45° console.log("======================="); //度[0,360) //弧度[0,2*PI) //度转弧度 function degree_to_r(degree) { //PI-->180° return (degree / 180) * Math.PI; } //弧度转度 function r_to_degree(r) { return (r / Math.PI) * 180; } var r = degree_to_r(90); console.log(r); console.log(r_to_degree(r)); console.log("======================="); //sin 30°= 0.5 ,asin(0.5)对应多少度呢 //asin(0.5)算出的是弧度单位 //范围在[-2PI,2PI] r = Math.asin(0.5); console.log(Math.floor(r_to_degree(r))); r= Math.acos(0.5) console.log(Math.floor(r_to_degree(r))); console.log("======================="); //返回一个坐标对应的角度,范围[-PI,PI] //Math.atan2(y,x); r = Math.atan2(-1,1); console.log(r_to_degree(r)); r = Math.atan2(0,-1); console.log(r_to_degree(r)); console.log("======================="); //Math.sqrt 开平方 console.log(Math.sqrt(16));//16的平方根 console.log(Math.sqrt(2)); //2的平方根 console.log("======================="); //计算两点之间的距离 function vector_distance(lhs_x,lhs_y,rhs_x,rhs_y) { var len = (lhs_x - rhs_x ) * (lhs_x - rhs_x ) + (lhs_y - rhs_y) * (lhs_y - rhs_y); return Math.sqrt(len); } console.log(vector_distance(0,0,1,1)); console.log("=======================");
Related recommendations:
Explanation of the new math and Number methods in JavaScript ES6
The above is the detailed content of A simple way to use Math in js. For more information, please follow other related articles on the PHP Chinese website!