获取正负夹角

const EPS=0.00000001;
//单个向量的弧度
function getSingleRadian(x) {
  const d1=x[0];
  const d2=Math.sqrt(x.reduce((acc, n) => acc + Math.pow(n, 2), 0));
  if(Math.abs(d1-d2)<EPS){
    return 0
  }
  return Math.acos(d1/d2);
}
//两个向量的夹角弧度
function getTwoRadian(x,y) {
  while (x.length>y.length){
    y.push(0);
  }
  while (x.length<y.length){
    x.push(0);
  }
  let mX = Math.sqrt(x.reduce((acc, n) => acc + Math.pow(n, 2), 0));
  let mY = Math.sqrt(y.reduce((acc, n) => acc + Math.pow(n, 2), 0));
  const d1=x.reduce((acc, n, i) => acc + n * y[i], 0);
  const d2=(mX * mY);
  if(Math.abs(d1-d2)<EPS){
    return 0
  }
  return Math.acos(d1/d2);
}
//两个向量的夹角弧度
function getRadian(x,y) {
  if(!y){
    return getSingleRadian(x)
  }else{
    return getTwoRadian(x,y)
  }
}
//获取角度0-180
function getAngle(x,y) {
  const ra=getRadian(x,y);
  return parseInt(ra*180/Math.PI*100000000)/100000000
}
//demo
const arr1=[8,8,8,8,8,8,8,8,8,8,8,8,8]
const arr2=[8,8,8,8,8,8,8,8,8,8,8,8,9]
const angle1=getAngle(arr1)
const angle2=getAngle(arr2)
const angle3=getAngle(arr1,arr2)
console.log(angle1,angle2,angle3)

  

原文地址:https://www.cnblogs.com/caoke/p/13711850.html