Square root calculation - actionscript-3

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 ???

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

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

Related

How to handle number and string types interchangibly when using input forms?

My problem is that as far as I know javascript can't handle number format in forms and converts everything to string.
I have a function that lets users select their macronutrient ratio percentages - the sum of carbs, fats, protein have to be sum of 100%.
I store users goal macros as a number in my database and I calculate current percentage totals like this:
const carbsPercentage = ((goalCarbs * 4) / goalCalories) * 100;
const fatsPercentage = ((goalFats * 9) / goalCalories) * 100;
const proteinPercentage = ((goalProtein * 4) / goalCalories) * 100;
Then using React-hook-form watch() method I track users form inputs to recalculate the total percentage:
const watchCarbsPercentage = watch('carbsPercentage');
const watchFatsPercentage = watch('fatsPercentage');
const watchProteinPercentage = watch('proteinPercentage');
const watchCalories = watch('calories');
// gets total percentage based on the sum of the other 3
const getTotalPercentage = () => {
const parsedCarbsPercentage = parseInt(watchCarbsPercentage) || 0;
const parsedFatsPercentage = parseInt(watchFatsPercentage) || 0;
const parsedProteinPercentage = parseInt(watchProteinPercentage) || 0;
const totalPercentage =
parsedCarbsPercentage + parsedFatsPercentage + parsedProteinPercentage;
return totalPercentage;
};
Because of this I get typescript error when I try to use parseInt:
const watchCarbsPercentage: number
Argument of type 'number' is not assignable to parameter of type 'string'.ts(2345)
I thought that typescript would infer that as soon as number is assigned to input it becomes string or am I wrong?
How do I handle this logic correctly?

Divs height relative to some number value inside the div

I have a set of blocks, each have some associated number. I need to make blocks height correspond to this number. For example
As you can see the bigger number - the higher is div.
But its not 1:1 related, right? Otherwise we would not even see the blocks with number "1" or "10". So I'm trying to figure out how to calculate this approximate heights. I know its more like mathematical task.
Update: Also values can be any fractions, including less than 1
Finally, we have a working function that solves this problem.
Suppose we have an array of blocks objects with id and relative number value.
function blockHeights(blocks) {
const MAX_HEIGHT_PX = 500;
let logs = [];
blocks.forEach((block) => {
if (block.value) {
logs.push(Math.log10(block.value));
}
});
const minLog = Math.ceil(Math.min(...logs));
const addition = minLog < 0 ? (1 - minLog) : 0;
const maxLog = Math.ceil(Math.max(...logs)) + addition;
const step = MAX_HEIGHT_PX / maxLog;
let blockHeights = {};
blocks.forEach((block) => {
blockHeights[block.id] = Math.round(step * (Math.log10(block.value) + addition));
});
return blockHeights;
}
----------------------------------------------------------
There is also another solution, which works better in my case: to use the formula from here: https://stats.stackexchange.com/a/281164/266299
and normalize all values to fit between your predefined min and max block height. This way the function is going to look like this:
function blockHeights(blocks) {
const MIN_BLOCK_HEIGHT_PX = 65;
const MAX_BLOCK_HEIGHT_PX = 300;
const maxMinDifference = MAX_BLOCK_HEIGHT_PX - MIN_BLOCK_HEIGHT_PX;
const min = Math.min(...Object.values(blocks));
const max = Math.max(...Object.values(blocks));
blocks.forEach(block=> {
result[block.id] = ((block.value - min) * maxMinDifference / (max - min)) + MIN_BLOCK_HEIGHT_PX;
});
return result;
}
Maybe can loop on each value and check if
if (largestValue > 100) {
percentage = (currentValue / largestValue) * 100
if ( percentage < 5 ) {
BlockXUIHeight = 5
BlockXUIWidth = 5
}
}

How can I order my string in as3

A complex question :
I've got this code (not the complete code, but the essentials for the question, I think) :
var $pmm:String;
var $pms:String;
var $bmm:String;
var $bms:String;
function get haute1():String { return $pmm; };
function get haute2():String { return $pms; }
function get basse1():String { return $bmm; };
function get basse2():String { return $bms; };
accueil.todayHaute_txt.htmlText = haute1;
accueil.todayBasse_txt.htmlText = basse1;
accueil.todayHauteSecond_txt.htmlText = haute2;
accueil.todayBasseSecond_txt.htmlText = basse2;
"haute1" is an hour (in 24h format). Something like "13h25".
It changes everyday.
Question : How can put them in ascending order in AS3 ?
Example : If haute1 = 15h20, haute2= 6h00, basse1= 11h and basse2 = 17h, the function would put them in this order :
"haute2", then "basse1", then "haute1" and finally "basse2".
Thx
EDIT
I add this code that I have. is it helping you ?
/ Assigns hours and tidal heights
$pmm = convdateheure($tpbs[1 + $deltapm]);
$pms = convdateheure($tpbs[3 + $deltapm]);
$bmm = convdateheure($tpbs[2 - $deltapm]);
$bms = convdateheure($tpbs[4 - $deltapm]);
function convdateheure($valeur:Number):String
{
var $heure:Number = Math.floor($valeur);
var $minute:Number = Math.floor(Math.floor(($valeur - Math.floor($valeur)) * 100) * 0.6);
var hoursLabel:String = "", minsLabel:String = "";
if ($heure == 24) $heure = 0; // Check if at the 24 hour mark, change to 0
if ($heure < 10) hoursLabel += "0" + $heure.toString(); else hoursLabel = $heure.toString();
if ($minute < 10) minsLabel += "0" + $minute.toString(); else minsLabel = $minute.toString();
return hoursLabel + ":" + minsLabel;
}
If you want to order some dates written in some String format:
One way would be, depending on you date string format, just to push them into array and sort them as strings, then read them all.
Another way would be to first parse those strings into Date instances, and push their Date.time property to array, sort it, then do reverse: parse all time values from sorted array into new Date instances then use Date.toString or similar.
Assuming that $valuer is a numerical value:
var timesArray:Array = new Array();
var convertedTimesArray:Array = new Array();
function sortTimes():void{
timesArray.push($valuer);
timesArray.sort(Array.NUMERIC);
}
function convertTimes():void{
convertedTimesArray = []; // clear the array
for (var i:int = 0; i < timesArray.length; i++){
var s:String = convdateheure(timesArray[i]);
convertedTimesArray.push(s);
}
}
That should give you one array of actual times, sorted in numerical order, and one array sorted in the same numerical order, but converted to String values using your function.

using this percentage function in Flash AS3

Hi I have this function I found
function valueToPercent($value:Number, $min:Number, $max:Number):Number {
var myPercent:Number;
var difference:Number = $max - $min;
myPercent = (($value - $min) / difference);
return myPercent;
}
How would I define those variables and get a result? I need to output various percentages which will become variables, which will then power a pie chart...
This didn't work, but I've obviously done it wrong
function valueToPercent($value:Number, $min:Number, $max:Number):Number {
var myPercent:Number;
var difference:Number = $max - $min;
myPercent = (($value - $min) / difference);
return myPercent;
}
valueToPercent(45, 0, 345);
Trace(valueToPercent);
Thanks!
You're almost there. When a method returns a value, you can asign it to a variable of type that it returns
var percentage:Number = valueToPercent(45, 0, 345);
trace(percentage);
and/or
trace(valueToPercent(45, 0, 345));

Other ways of counting number of keywords in a complex string

I am reading a file which contains approx 1200 words in the following format:
words:a:/zenb:/fixx:/wew:/sina:/benb:/sixx:/hew:/bin
I need to find how many keywords are there in that text file, by keyword i mean:
zen fix we sin ben six he bin
Right now I am trying to do it with RegExp like this:
var s:String = "words:b:sa:/zenb:/fixx:/wew:/sina:/benb:/sixx:/hew:/bin";
var pattern:RegExp = /:/+/g;
var results:Array = s.match(pattern);
trace(results.length);
Its producing an error, since I am a beginner I really don't understand how this RegExp work , are there any alternate methods to get the same results?
Thanks
Your var pattern:RegExp = /:/+/g; has a syntax error, you skipped a backslash \ change this to :
var pattern:RegExp = /:\/+/g;
and it should work, Alternatively with this format you can use the String split method to get the total word count. Try this:
var s:String = "words:b:sa:/zenb:/fixx:/wew:/sina:/benb:/sixx:/hew:/bin";
var wordCount:Number = s.split(":/").length -1;
trace( wordCount );
Hope that works.
package
{
import flash.display.Sprite;
public class CountWordsExample extends Sprite
{
public function CountWordsExample()
{
super();
// 8 7 0
trace(countWords(
"words:b:sa:/zenb:/fixx:/wew:/sina:/benb:/sixx:/hew:/bin",
":/"),
countWords(
"words:b:sa:/:/fixx:/wew:/sina:/benb:/sixx:/hew:/bin",
":/"),
countWords(
"words:b:sa::zenb::fixx::wew::sina::benb::sixx::hew::bin",
":/"));
}
public static function countWords(words:String, delimiter:String,
countBlanks:Boolean = false):uint
{
var result:uint;
var wordPointer:int = -1;
var delimiterPointer:int;
var delimiterLength:uint = delimiter.length;
if (words.length >= delimiterLength)
{
do
{
delimiterPointer = wordPointer;
wordPointer = words.indexOf(
delimiter, wordPointer + delimiterLength);
if (countBlanks ||
// we moved by more characters, then the length of
// delimiter
wordPointer - delimiterLength > delimiterPointer)
result++;
}
while (wordPointer > -1)
}
return result;
}
}
}
Here's an example of how to count words without ever creating additional arrays or sub-strings of the original string. It also verifies that the words counted have at least one character length.