Issues with JavaScript Calculation - javascript

Trying to do a simple JavaScript calculation
var money = $("#money").val();
var percentRate = "{{ $money->percent }}"/100;
var incomeMoney = money * percentRate;
If the $amount->percent is a whole number it will give a correct figure but if I use a decimal point it won't.
Eg if I assign 23 to $money->percent it will give me the correct figure but if I assign decimal like 23.5 it will give a wrong figure.
I believe the system is rounding the percentRate to 0.23 instead of 0.235. How do I get around this, Please?
Full code -
...

Related

Is there a way to cut off a part of a decimal in Javascript?

I have a number that increases every second by addition. The problem is that it contains way too many decimals. An example of an output which I do not want would be something like 1.5999999999999999 or 1.600000000001. I have tried using the toFixed method, passing in 2 as it's value, and I am still getting the issue. I have also tried using the Math.round(number * 100) / 100 and am still getting uggly decimals.
How can I get an output that only contains a specified number of decimal points? I want to be able to choose how the number rounds. The function to round should be something like this:
function round(numberToRound, afterDecimals){
//Rounding code which takes into the account the number of decimal values I wish to display should go here
}
Thank you.
I am so sorry, I didn't call the function in the right place. The function works as expected, I just wasn't updating the innerHTML correctly.
Again, I am sorry for overlooking this.

How to calculate logarithm with base N for big integer?

I'm using this BigInteger.js for some calculations:
let myBigInt = bigInt(20).pow(200) // gets 160693804425899027554196209234116260252220299378279283530137600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
I'd like to apply the logarithm to the big integer but in the docs I could not find any matching function. How can I implement a log(baseN, valueX) function for the BigInteger.js library?
Note: let myLogarithm = myBigInt.log(baseN) is not a valid implementation.
Note: After a lot of try&error I did found a working solution my own and I will post it here because I'm pretty sure there are a few more people then me that also gots faced with the same issue right there. So I hope, I could help :)
Have a look at wikipedia, as I did because theres a very nice article about baseConversion.
Below you can find a function for Math.log(base, value) that is able to calculate the log(base) from a value.
Math.log = (function() {
var log = Math.log;
return function(base, n) {
return log(n)/(base ? log(base) : 1);
};
})();
To calculate the logarithmToBaseN for bigInt-values just use this line of code:
let logarithmToBaseN = (myBigInt.toString().length * Math.log(baseN, 10) + Math.log(baseN, parseFloat("0." + myBigInt))) - 1);
Edit: This soltuion is a tiny workaround bacause parseFloat("0." + myBigInt) converts a big value like 100000 to a really small one like 0.100000,... what causes that it will be in integer precision.
According to #Jonas W's comment: The solution is very accurate for lower bases like (5, 10, ...) combined with low values like 10, 1000, 100000 - but for really big values like bigInt(20).pow(200) is it not.
Note: Using parseFloat (IEEE 754 double precision floating-point) means, you have a maximum of 52 bits of precision, which is a bit more than 15 decimal places. After that - the accuracy will be killed.
Note: For really big values bigInt(20).pow(200) combined with really big Bases like 100*(and more) it seems to be pretty accurate again.
Greetings, jonas.

Modulo - calculations error

Let me be brief. I'm trying to calculate
alert((Math.pow(7,35))%71)
but it gives me 61, when the result must be 70. What's wrong?
As others mentioned before with regards to using Math.pow(7,35), this resulting number is way too big for Javascript to handle.
To resolve your problem you need to use an external javascript library.
(Or write your own ;) )
Here are some examples of Javascript libraries that handle big numbers.
BigNum
Bignumber
I hope it helps.
The number you're using is too big for javascript. The max size of an int is 2^53 -- which is less than 7^35.
The only value which requires more precision is an intermediate result. So the problem can also be avoided without the need for higher precision variables when you have an algorithm that doesn't need the problematic intermediate result.
The following formula can be useful for that:
(a.b) % c = (a % c)(b % c) % c
This means Math.pow(7,35)%71 = ((Math.pow(7,17)%71) * (Math.pow(7,18)%71)) % 71.
Now the intermediate results are smaller, but might still be too big. So we need to split up further and to apply the modula operator on smaller intermediate results.
So you can do something like this:
Math.pow((Math.pow(7,7)%71),5)%71
But you probably need to do this for integer numbers wich are variable (otherwise, you could have avoided the problem by hardcoding the result).
So, you need to have an idea about the range of values you can expect and to define an algoritm that splits up the power calculation into pieces that will always have results that are small enough when the input is within the expected range.
And whatever you choose for a calculation like this, calculation with higher precision variables (using a specialized library) or a specilized algoritm, you should always assert the input to make sure your calculation returns a value only when you are sure it can deliver a correct value. Otherwise your implementation becomes unreliable for anyone who isn't aware of the range in which it is valid. Otherwise return an exception with a message that tells clearly which input or combination of inputs is the problem and why.

Javascript rounding down

So I've looked into this for several hours before finally giving up and asking help.
I'm currently trying to form fill a character sheet for Pathfinder (D&D 3.5 equivalent) using adobe acrobat. I want to make it so when I fill in my strength score it will auto fill out anything that has to do with strength.
More specifically I need it to take my ability score divide by two and subtract 5 for my ability modifier. But when I use 17 for instance as my Strength score my modifier is 4. I need it to round down not up.
I tried to subtract 5.5 instead and that works until its 10 or lower. At which point I have the opposite problem.
My current code is Strength/2-5
Use Math.floor() like this:
var score = 17.0;
result = Math.floor((score / 2) - 5);
alert(result)
Output:
3
Original:
Strength/2-5
(it worked but it needed to round down instead of up)
Final:
var a = this.getField("Strength")
event.value = Math.floor((a.value - 10) / 2)
Thank you for trying everybody! Process of elimination gets it done

Using Math.exp() in Javascript with BigDecimal for large floating point numbers

I'm attempting to perform the following calculation in Javascript:
e^x / (1 + e^x)
where x is a long floating point number.
In this instance, I require accuracy to at least the 10th decimal place.
I've been using BigDecimal to accurately handle the floating point numbers, as suggested at The Floating Point Guide.
My first attempt of:
var foo = new BigDecimal(myVeryLongFloatingPoint)
var bar = Math.exp(foo);
var spam = bar.divide(bar.add(new BigDecimal("1")));
led to the error (where xxxxx is the floating point number):
TypeError: Object xxxxx has no method 'add'
So I attempted to tried convert bar into a BigDecimal object:
var foo = new BigDecimal(myVeryLongFloatingPoint)
var bar = new BigDecimal(Math.exp(foo));
var spam = bar.divide(bar.add(new BigDecimal("1")));
which in turn leads to the error (where xxxxx is the floating point number):
BigDecimal(): Not a number: xxxxx
Where am I going wrong?
Is this a sensible approach to handling this kind of calculation with floating points where a high degree of precision is required?
You should pass strings to BigDecimal:
var bar = new BigDecimal(Math.exp(foo).toString());
There are a few mathematical approaches that might be useful. If x is positive and reasonably large, then you're taking the ratio of two large number and this will reduce your final precision. Instead, you might:
Use 1./(1. + e^(-x)) instead.
For large x, this is approximately 1.-e^(-x), and the bigger x is, the better the approximation (e.g., if x=100, then your error would be in the 86th digit).
(Honestly, one should verify this before using it, I'm just going of off memory here an not writing anything down, but if this looks useful, I could grab a pencil...)
Math.exp only works on normal Numbers and cannot operate on BigDecimals. Math.exp is probably converting foo to NaN (or something like that) before continuing.
You should look for an exponentiation method inside your BigDecimal class. I looked at the source and I think there is a BigDecimal.pow method you could use instead.

Categories