Alan Spurlock
Alan Spurlock

Reputation: 107

Converting excel formula to javascript problem

Formula in excel

=AVERAGE($B$20,$C$20)/((PI()/4)*(AF21+0.01)^2)

is basically this:

=AVERAGE(5000,4500)/((PI()/4)*(0.3859+0.01)^2)

Which out puts as 38586

Formula in javascript

function calcUltimate(max, min, radius) {
        return (((max + min) / 2) / (Math.pow(((Math.PI / 4) * (radius + 0.01)), 2))).toFixed(0);
    }

Output is 49130

I can not get the outputs to match at all. I don't know what I am doing wrong here.

Upvotes: 0

Views: 104

Answers (3)

Patrick Evans
Patrick Evans

Reputation: 42736

Your operations are going in the wrong order. To debug formulas simply break them down into separate operations saving the results in different variables. This way you can more easily read the operations going on.

function calcUltimate(max, min, radius) {
  var avg = (max + min) / 2;
  var quarterPie = Math.PI / 4;
  var adjustedRadius = radius + 0.01;

  //the adjusted radius is the one being squared
  //** is power, shorter than using Math.POW() for
  //supporting browsers
  var squareAdjustedRadius = adjustedRadius**2;

  //if you don't want the decimal part but still want a number
  return Math.floor( avg / (quarterPie * squreAdjustedRadius) )
  //if you actually want a string version
  return (avg / (quarterPie * squreAdjustedRadius)).toFixed(0)
}

Demo

console.log(calcUltimate(5000,4500,0.3859))

function calcUltimate(max, min, radius) {
  var avg = (max + min) / 2;
  var quarterPie = Math.PI / 4;
  var adjustedRadius = radius + 0.01;
  var squareAdjustedRadius = adjustedRadius**2;

  return Math.floor(avg / (quarterPie * squareAdjustedRadius));
}

Upvotes: 0

Ryan Cogswell
Ryan Cogswell

Reputation: 80966

It should be (you're putting too much into Math.pow call):

function calcUltimate(max, min, radius) {
        return (((max + min) / 2) / ((Math.PI / 4) * Math.pow((radius + 0.01), 2))).toFixed(0);
}

Upvotes: 1

V. Sambor
V. Sambor

Reputation: 13369

Try this please:

function calcUltimate(max, min, radius) {
   return parseInt((((max + min) / 2) / ((Math.PI / 4) * Math.pow((radius + 0.01), 2))).toFixed(0));
}

Upvotes: 2

Related Questions