Operator // in JavaScript : 5.0 // 2.0 = 5? - javascript

Is there a // operator in JavaScript?
Because in Python we have:
5 // 2.0 # => 2.0
5 / 2.0 # => 2.5
So I tried in JavaScript:
5.0//2.0
and I got 5! What's going on there?
I read that there is no such a thing as a // operator in JavaScript. In this case, why didn't I get an exception or, better, an error from the lexer?
I used this line:
document.write(eval("5.0//2.0"));
In Firefox 3.6.23.

// is a comment in javascript.
Try:
5 / 2; //yields 2.5
Math.floor(5/2); //yields 2
Also do not use eval.
Just do document.write(5/2);

In JavaScript, // is not an operator, it denotes a comment.

// is used for commenting in JavaScript.

// starts a comment. To do integer division, first perform a regular division using / and then round it. This can be done with &-1, ^0, |0 or ~~, in order from fast to slow as measured on my laptop. There is a measurable difference between the first three but it's small. The last one is really slow in comparison.
Putting it all together, 5/2&-1 will yield 2. It rounds towards zero.

You want to use ~~ 5/2 to get 2. NO need to download math. library

Related

Calculation result different in javacript and lua

I'm currently creating my own bot made with NodeJS and having a issue where my formula won't calculate the same way it does in Lua
Here is a example:
XP = 79878
math.floor((1/4+XP/125)^0.5-1/2)
Lua: returns 24
JavaScript: returns 639
If anyone knows how to make this formula work with JavaScript please provide an example below.
Thanks.
The ^ operator in Javascript does a XOR operation, rather than raising something to a power. In recent versions of Javascript (Node.js 8 seems to support it, I'm not sure about earlier versions) you can use the ** operator instead; if you need to support earlier versions, you should use Math.pow().
// newer code
Math.floor((1/4 + XP/125) ** 0.5 - 1/2)
// older code
Math.floor(Math.pow(1/4 + XP/125, 0.5) - 1/2)
You should use like this:
Math.floor(Math.pow(1/4+(XP/125), 0.5)-1/2);

Can crypto.getRandomValues(new Uint32Array(1))[0] / lim ever be negative?

Curious whether the expression crypto.getRandomValues(new Uint32Array(1))[0] / lim can ever be negative.
The code I'm converting puts a Math.abs wrapper around it, but some of us think that it's impossible for it to be negative, so just wanted to see what the rest of you think?
var lim = Math.pow(2, 32) - 1;
crypto.getRandomValues(new Uint32Array(1))[0] / lim);
This is the related question for more context:
Converting getRandomValue.browser from cuid to Typescript?
The library has a getRandomValue() nodejs function that looks like this:
import * as crypto from "crypto"
var lim = Math.pow(2, 32) - 1;
export function getRandomValue () {
return Math.abs(crypto.randomBytes(4)
.readInt32BE(0) / lim)
}
I think for the browser, the Math.abs call was kept even though it seems it is not necessary, and quite possibly incorrect.
In this case, the use of Math.abs() would be wrong!
The value in question, so says the declaration above, is UInt32 ... unsigned 32-bit integer.
This simply means that the leftmost bit (most significant bit) is not to be interpreted as a sign-bit. This does not, however, prevent you from inadvertently using the value in some context which would assume that MSB=1 means "negative."
Nonetheless, it would be wrong for you to use abs() because this would convert the entire bit-pattern, if it finds that MSB=1, into an entirely different bit-pattern. Since the MSB is simply "one of the 32 bits which comprises the value," it is dead-wrong to do anything to it which assumes that it's a sign-bit. And you also want to take care that it never gets displayed as a negative number, because it isn't. This quantity is 32 bits long, not 31+sign. Be sure it always looks that way.

Rounding in JS: inconsistent and unexpected behaivior

I'm dealing with relatively small and simple numbers. I first tried to do the rounding (2 signs after digit) with infamous toFixed. It's a known issue: sometimes it works incorrectly. But what struck me is the fact that it also works inconsistently:
(0.395).toFixed(2); // "0.40"
(0.295).toFixed(2); // "0.29"
These numbers are very similar, 3 signs after digit and yet different behavior.
So, I decided to switch to using Math.round. Shortly, I encountered another problem:
Math.round(0.35055 * 10000) / 100; // produces 35.05 instead of 35.06
Is Math.round also problematic? Then, what method should be used?
Unfortunately JavaScript is known to have such precision issues, issues that are better explained in the following question: Is floating point math broken?, as pointed in the comments.
If you require a greater degree of numerical accuracy, I would suggest you to use a library such as BigNumber, which also comes with its own toFixed method.
Your example would look something like this:
var a = new BigNumber('0.35055');
a = a.times(10000)
a = a.dividedBy(100)
console.log(a.toFixed(2)); //would log "35.06"
For brevity you can also chain the operations, like this: a.times(10000).dividedBy(100).toFixed(2)
I think this is working as designed. Keep in mind these numbers are stored in base 2, so there is a loss of precision when converting to and from base 10. And you have to look at these conversions if you want to understand why it looks inconsistent. If you have a fixed number of decimals that you want to keep precisely, you can use integers for operations and convert only for display.

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

Categories