Q Lion
Q Lion

Reputation: 41

How can I do this math formula in JavaScript

I need to work out what is the volume of liquid left in a cylinder on its side in JavaScript, how will I do the following in code?

enter image description here

Upvotes: 1

Views: 946

Answers (3)

Q Lion
Q Lion

Reputation: 41

Hi Shubh and Matt Major Thanks!!!! i manage to do it via the following.

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));

Upvotes: 1

K&#233;vin Bibollet
K&#233;vin Bibollet

Reputation: 3623

You can use:

  • ** operator for powers (or Math.pow)
  • Math.acos for cos^(-1)
  • Math.sqrt for the square root

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;
}

Upvotes: 1

Shubham Dixit
Shubham Dixit

Reputation: 1

You can try something like this.I have used Math.acos and Math.pow.And rest is simple Mathematics.

Since Math.acos returns NaN if the number is not between (-1 and 1) ,so I have checked before if the acos returns 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")

Upvotes: 1

Related Questions