如何在JavaScript中执行此数学公式

时间:2019-06-12 07:28:10

标签: javascript math

我需要计算出在JavaScript中位于其侧面的圆柱体中剩余的液体量,如何在代码中执行以下操作?

enter image description here

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的操作。我使用过Math.acosMath.pow。其余的都是简单的数学。

  

由于Math.acos如果数字不在(-1和1)之间,则返回NaN   ,所以我之前检查过acos是否返回NaN

function volume(diameter, depth, length) {
  let R = diameter / 2;

  if (Math.acos((R - depth )/ R) != NaN) {
    let a = Math.pow(R, 2) * Math.acos((R - depth) / R) - (R - depth) * (Math.pow((2 * R * depth - Math.pow(depth, 2)), 0.5))

return a * length;
 } else {
return "Cylinder radius can't be less than depth"

  }
}
// returns volume in meter cube
// 1 meter cube =1000l
console.log(volume(1.08, 0.72, 2.40)*1000,"L")

答案 1 :(得分:1)

您可以使用:

  • **的幂运算符(或Math.pow
  • Math.acos for cos^(-1)
  • Math.sqrt表示平方根

console.log(calculateVolumeInCylinder(1.08, 2.4, 0.72))

/**
 * @param {number} Dm - Cylinder diameter in meters.
 * @param {number} L - Cylinder length in meters.
 * @param {number} Dp - Depth in meters.
 * @returns {number} Volume in liters.
 */
function calculateVolumeInCylinder(Dm, L, Dp) {
  let R = Dm / 2,
    // R^2 cos^-1(R-D/R)
    sA = R ** 2 * Math.acos((R - Dp) / R),
    // (R-D)
    sB = (R - Dp),
    // SQRT(2RD-D^2)
    sC = Math.sqrt(2 * R * Dp - Dp ** 2);
    
  return (L * (sA - sB * sC)) * 1000;
}

答案 2 :(得分:1)

嗨Shubh和Matt Major谢谢!!!我设法通过以下方式做到这一点。

function round(d)
// Returns a number rounded to 4 decimal places.
{ var multiplier = 10000;
  return Math.round(d*multiplier) / multiplier;
};


function negative(n)
{ if(n<0)
     complain("Negative input");
  return (n<0);
}

function calculate(vdiam,vlen,vdepth){ 

  //var vdiam  = 1.08;
  //var vlen   = 2.40;
  //var vdepth = 0.72;
  var res = 0;  //result


  //Convert inputs to numbers
  d = new Number(vdiam);
  l = new Number(vlen);
  h = new Number(vdepth);
  r = d/2;

  if(negative(d)) return;
  if(negative(l)) return;
  if(negative(h)) return;

  //make sure it's all kosher
  if(h>d)
	{ console.log("Depth exceeds diameter");
      return;
    }



  //calculate
  var segArea =r*r*Math.acos((r-h)/r) - (r-h)*Math.sqrt(2*r*h-h*h);
  res = segArea*l;
  if(isNaN(res))
	{ console.log("Inputs must be positive numbers");
	  res = "";
      return;
	}

	res = res*1000;
  
  return round(res);

}


alert(calculate(1.08,2.40,0.72));