Question

want to calculate square root of given input so i used this code

var no1:Number = 2;
var no2:Number; //input for calculation
var total:Number;
total=Math.pow(no2,(1/no1));

its working , but i faced problem such as:- if i give

no2 = 25;

then it shows

total=4.9999999

to overcome this problem i used below code

total=Math.ceil(Math.pow(no2,(1/no1)));

but its okey for 25 .

total = 5

problem was if i give 21,22,23,24

for all this input it shows 5

so is there any other solutions ???

Was it helpful?

Solution

If you want to take the nth root. You can feed the output of your function into arbitrary rounding function like this:

/**
 * Rounds input number to specified number of decimal places. For example
 * round(4.568, 2) will return 4.57, and round(4.99, 2) will return 5.
 */
function round(num:Number, toDecimalPlaces:uint) {
   var factor:uint = Math.pow(10, toDecimalPlaces);
   return Math.round(num * factor) / factor;
}

/**
 * Returns nth root to two decimal places.
 */
function nthRoot(n:uint, num:Number) {
   return round(Math.pow(num, (1 / n)), 2);
}

OTHER TIPS

There's a function for that.

var total:Number = Math.sqrt(no2);

my actual code was like this

var str:String=view.numDisplay.text;//input string
var power:Number = Number(inString.charAt(inString.indexOf('√') - 1));//to get the value before √ i.e no1
var no1:Number;
var no2:Number;
var total:Number;
if(power)
   no1=v;
else
   no1=2;
no2=getSubTerm();//method to find no2 it returns the number for calculation
total=Math.ceil(Math.pow(no2,(1/no1)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top