Reduce number of decimals - actionscript-3

In AS3, from a division I get a number like this one: 0.9130406010219044.
Is there any way to reduce the number of decimals (aside from multiplying that number for one million)? Is there a way to reduce the numbers BEFORE the division is performed?

Got the following function from this link, which rounds to an arbitrary number of decimals:
public function trim(theNumber:Number, decPlaces:Number) : Number {
if (decPlaces >= 0) {
var temp:Number = Math.pow(10, decPlaces);
return Math.round(theNumber * temp) / temp;
}
return theNumber;
}
// Round a number to two decimal places trace(trim(1.12645, 2));
// Displays: 1.13
Note: I slightly changed the function definition by adding types. See the link for explanation and original source code. Also made it return theNumber if decPlaces is less than or equal to zero.

var myNumber:Number = 74.559832;
trace(myNumber.toFixed(4)); //74.5598
trace(myNumber.toFixed(2)); //74.56
AS3 Documentation: Number class

If you just want to display the result (you didn't specify) then a simple bit of String manipulation will yield the fastest result:
0.9130406010219044.toString().substr(0, 4); // 0.91

Take a look at NumberFormatter.fractionalDigits
Or, if you're working in Flex: mx:NumberFormatter.precision / s:NumberFormatter.fractionalDigits

Try some of the answers here on for size:
How to deal with Number precision in Actionscript?
If you use a NumberFormatter, make sure to specify rounding (it's most likely you'll want nearest).

If you need Number as result and performance, I would say this solution is more efficient than the Math.pow()
If you need 3 decimals just change 100 by 1000.
var myNumber:Number = 3.553366582;
myNumber = (( myNumber * 100 + 0.5) >> 0) / 100;
//trace = 3.55
demonstrating the rounding :
var myNumber:Number = 3.557366582;
myNumber = (( myNumber * 100 + 0.5) >> 0) / 100;
//trace = 3.56
Regarding the Number.toFixed() returning a String I guess it's because it returns 2 decimals in any case:
For instance :
Number(3).toFixed(2); // trace 3.00 so it has to be a String.

Related

Convert from one range to another

I have two sets of ranges that I need to be translated from one to the other.
The first range is -100 ↔ 100 with 0 being default.
The second range is 0.0 ↔ 10.0 with 1 being default.
I am working in AS3 with the first range and the second range is a python class and I need these numbers to line up.
I am adjusting brightness of a video in realtime with a slider. The video filter accepts values between -100 ↔ 100. I need to then take that value and pass it to a python script but it only accepts values from 0.0 ↔ 10.0
I tried this function I found on the net, but it doesn't translate the values correctly in this particular case.
private function convertRange(originalStart:Number,originalEnd:Number,newStart:Number,newEnd:Number,value:Number):Number
{
var originalRange:Number = originalEnd - originalStart;
var newRange:Number = newEnd - newStart;
var ratio:Number = newRange / originalRange;
var newValue:Number = value * ratio;
var finalValue:Number = newValue + newStart;
return finalValue;
}
Is this even possible? Hopefully my question is clear, please let me know if it needs clarification.
This is the python class I am referring to: https://github.com/dubhater/vapoursynth-adjust It uses the second range whereas AS3 uses the first range.
Why not trying something like this :
function from_AS_to_PY(as_value:Number): Number // as_value : -100 ----- 0 ----- 100
{
var py_value:Number = (as_value / 100);
py_value = (py_value <= 0 ? py_value : py_value * 9) + 1;
return py_value;
}
function from_PY_to_AS(py_value:Number): Number // py_value : 0 - 1 --------- 10
{
var as_value:Number = (py_value <= 1 ? py_value - 1 : ((py_value - 1) / 9)) * 100;
return as_value;
}
trace(from_AS_to_PY(-100)); // gives : 0
trace(from_AS_to_PY(-99)); // gives : 0.01
trace(from_AS_to_PY(-1)); // gives : 0.99
trace(from_AS_to_PY(0)); // gives : 1
trace(from_AS_to_PY(1)); // gives : 1.09
trace(from_AS_to_PY(99)); // gives : 9.91
trace(from_AS_to_PY(100)); // gives : 10
//---------------------------------------------------
trace(from_PY_to_AS(0)); // gives : -100
trace(from_PY_to_AS(0.01)); // gives : -99
trace(from_PY_to_AS(0.99)); // gives : -1
trace(from_PY_to_AS(1)); // gives : 0
trace(from_PY_to_AS(1.09)); // gives : 1
trace(from_PY_to_AS(9.91)); // gives : 99
trace(from_PY_to_AS(10)); // gives : 100
Hope that can help.
There is a fundamental difficulty with the problem. You are trying to fit three point of one range onto another range. If you were just interested in matching the two end points that would be easy you can use a linear interpolation y = 10 * (x+100) /200 or simply y = (x+100)/20 or equivalently y=x/20+5. The problem is it this does not match the default value and x=0 -> 5.
This might be the solution you want. However if it is important that he default values match you need to use a non-linear solution. There are many possible solutions. You can use a piecewise-linear solution like akmozo solution, which needs an if statement. if x<0 then y = x/100+1 else y = 1 + 9 x /100. The problem with this one is that you do not get a smooth response. Consider adjusting the slider from min to max, you see a very slow increase in brightness to start with and then it starts to increase much faster once you pass zero.
The big difference between the first half of the range and the second half suggests an exponential type solution. y = A exp(b x). Taking y = exp(x * ln(10)/100) matches the center point and the top end, the bottom end is just a little bit high at 0.1, rather than zero. This might be fine, if not you could find an exponential solution y = A exp(b x)-c which matches all three points.
Another possibility is using a power. An equation like y = A pow(x,n). A bit of calculation shows y=10 pow(x/200+0.5),3.321928095) matches all three points. The constant 3.321928095 = ln(0.1)/ln(0.5).
In the diagram the black curve is a simple linear solution. The red curve is the piecewise linear one, the green is the exponential one then the blue is the power.

Adding two numbers don't get correct result

I try to add two numbers, but don't get correct result
var n1:Number = 2785077255;
var n2:Number = 100000097214922752;
trace(Number(n1 + n2));//trace 100000100000000000, not 100000100000000007
trace((Number.MAX_VALUE - Number(n1 + n2)) > 100);//trace true
When I got the wrong result, I thought it exceed the Number's max value,so I test it and it doesn't trace false as I thought.
Yes, the problem is in Number as #Phylogenesis mentioned, it's actually 64 bit double with 52 bits for mantis, but your result exceededs that.
The good news are that there is a workaround for that, event two :)
Use some BigInteger/LongInt AS3 impelementation (you can google several of them), for instance BigInteger from as3crypto, or LongInt from lodgamebox
It's currently only for multiplying, but you can modify that solution as a small task. For best performance (without creation of temporary arrays/byte arrays) you can use that utility method that I created once (it's based on LongInt from lodgamebox library)
/**
* Safe multiplying of two 32 bits uint without precision lost.
*
* Usage:
* Default behaviour (with 64 bit Number mantis overflow):
* uint(1234567890 * 134775813) = 1878152736
*
* Fixed correct result by that method:
* uint(1234567890 * 134775813) = 1878152730
*
* #param val1
* #param val2
* #return
*
*/
public static function multiplyLong(val1:uint, val2:uint):uint
{
var resNum:Number = val1*val2;
//52 bits of mantis in 64 bit double (Number) without loose in precision
if(resNum <= 0xFFFFFFFFFFFFF)
return uint(resNum);
//count only low 32 bits of multiplying result
var i:uint, mul:Number, ln:uint=0, hn:uint=0, _low:uint = val1;
for (i = 1<<31; i; i >>>= 1)
{
if(val2 & i)
{
mul = _low * i;
ln += mul & uint.MAX_VALUE;
}
}
_low = ln;
return _low;
}

AS3: can't figure out Math.random

I'm very bad at math, so i can't figure out why this isn't working. It should calculate a random number between 0 and 360.
var minDegree:int = 0
var maxDegree:int = 360
function randomDegree (minDegree:Number, maxDegree:Number):Number
{
return (Math.random() * (maxDegree - minDegree + minDegree));
trace(randomDegree)
}
I assume you actually want integers, right? This is the actual code:
private function randRange(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
I'm posting it because #Xenophage's answer is not correct. And it's not correct because of the fact that Math.random Returns a pseudo-random number n, where 0 <= n < 1. (reference). What this means is that if you pass 0 as minimum and 360 as maximum, the biggest number you can get is 359 because:
(Math.random() * (maxDegree - minDegree) + minDegree);
(0.99999 * (360 - 0) + 0) = 359
So the upper solution would work better :) If you are not looking for an integer - let me know.
Edit: I've made the random to return more precise number, as if it was simply 0.99 it would calculate to 354 instead of 359. Either ways won't go up to 360.
And yes, I know you need degrees, so 0 is similar to 360 if you are not doing some precise calculations, but I had to mention it as it's a Math.random problem, not a degrees problem.
You were very close, move the closing parenthesis over a little. Multiplying the difference between max and min, then adding min back on to bring the value back into the proper range. I find it easy to try some examples using a simple calculator and seeing if the results make sense.
var minDegree:int = 0
var maxDegree:int = 360
function randomDegree (minDegree:Number, maxDegree:Number):Number
{
return Math.min(maxDegree, Math.random() * (maxDegree - minDegree) + minDegree + .01);
}
trace(randomDegree(minDegree, maxDegree));

How can I round an integer to the nearest 1000 in Pascal?

I've got a Integer variable in Pascal. Is there any possible function I can use that can round that value to the nearest 1000, for example:
RoundTo(variable, 1000);
Does anything of the sort exist? Or is there another method I should try using?
Thanks!
The general solution for this kind of problem is to scale before and after rounding, e.g.
y = 1000 * ROUND(x / 1000);
Use RoundTo(variable, 3).
The second parameter specifies the digits you want to round to. Since you want to round to 1000 = 103 you need to specifiy 3, not 1000.
The documentation for RoundTo says:
function RoundTo(const AValue: Extended; const ADigit: TRoundToEXRangeExtended): Extended;
Rounds a floating-point value to a specified digit or power of ten using "Banker's rounding".
ADigit indicates the power of ten to which you want AValue rounded. It can be any value from –37 to 37 (inclusive).
The following examples illustrate the use of RoundTo:
RoundTo(1234567, 3) = 1235000
(I left out parts not relevant to your question)
Side-note: RoundTo uses Banker's round, so RoundTo(500, 3) = 0 and RoundTo(1500, 3) = 2000.
x = 1000*(x/1000), or x = x - (x mod 1000)

Howto convert decimal (xx.xx) to binary

This isn't necessarily a programming question but i'm sure you folks know how to do it. How would i convert floating point numbers into binary.
The number i am looking at is 27.625.
27 would be 11011, but what do i do with the .625?
On paper, a good algorithm to convert the fractional part of a decimal number is the "repeated multiplication by 2" algorithm (see details at http://www.exploringbinary.com/base-conversion-in-php-using-bcmath/, under the heading "dec2bin_f()"). For example, 0.8125 converts to binary as follows:
1. 0.8125 * 2 = 1.625
2. 0.625 * 2 = 1.25
3. 0.25 * 2 = 0.5
4. 0.5 * 2 = 1.0
The integer parts are stripped off and saved at each step, forming the binary result: 0.1101.
If you want a tool to do these kinds of conversions automatically, see my decimal/binary converter.
Assuming you are not thinking about inside a PC, just thinking about binary vs decimal as physically represented on a piece of paper:
You know .1 in binary should be .5 in decimal, so the .1's place is worth .5 (1/2)
the .01 is worth .25 (1/4) (half of the previous one)
the .001 is worth (1/8) (Half of 1/4)
Notice how the denominator is progressing just like the whole numbers to the left of the decimal do--standard ^2 pattern? The next should be 1/16...
So you start with your .625, is it higher than .5? Yes, so set the first bit and subtract the .5
.1 binary with a decimal remainder of .125
Now you have the next spot, it's worth .25dec, is that less than your current remainder of .125? No, so you don't have enough decimal "Money" to buy that second spot, it has to be a 0
.10 binary, still .125 remainder.
Now go to the third position, etc. (Hint: I don't think there will be too much etc.)
There are several different ways to encode a non-integral number in binary. By far the most common type are floating point representations, especially the one codified in IEEE 754.
the code works for me is as below , you can use this code to convert any type of dobule values:
private static String doubleToBinaryString( double n ) {
String val = Integer.toBinaryString((int)n)+"."; // Setting up string for result
String newN ="0" + (""+n).substring((""+n).indexOf("."));
n = Double.parseDouble(newN);
while ( n > 0 ) { // While the fraction is greater than zero (not equal or less than zero)
double r = n * 2; // Multiply current fraction (n) by 2
if( r >= 1 ) { // If the ones-place digit >= 1
val += "1"; // Concat a "1" to the end of the result string (val)
n = r - 1; // Remove the 1 from the current fraction (n)
}else{ // If the ones-place digit == 0
val += "0"; // Concat a "0" to the end of the result string (val)
n = r; // Set the current fraction (n) to the new fraction
}
}
return val; // return the string result with all appended binary values
}