Calculation result different in javacript and lua - javascript

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

Related

issue with floating point precision js

I am experiencing the following bug in my JS.
(1.001 * Math.pow(10, 3))
Instead of returning 1001 this returns 1000.99999999. I am trying to eradicate this bug and have been looking at using this big.js library.
I am unsure what to do to fix this issue.
I have tried the following but it doesn't seem to work.
var x = new Big(10);
(1.001 * x.pow(3));
This produces the same bug as without the library.
You have to use Big.js that way, I think you have to forget using conventional operators :
console.log(Big(1.001).times(Big(10).pow(3)))
<script src="https://cdnjs.cloudflare.com/ajax/libs/big.js/3.2.0/big.min.js"></script>

Duplicates found in JavaScript created UUID from browser ad unit [duplicate]

This relates to this question. I am using the code below from this answer to generate a UUID in JavaScript:
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
This solution appeared to be working fine, but I am getting collisions. Here's what I have:
A web application running in Google Chrome.
16 users.
about 4000 UUIDs have been generated in the past two months by these users.
I got about 20 collisions - e.g., a new UUID generated today was the same as about two months ago (different user).
What is causing this issue and how can I avoid it?
My best guess is that Math.random() is broken on your system for some reason (bizarre as that sounds). This is the first report I've seen of anyone getting collisions.
node-uuid has a test harness that you can use to test the distribution of hex digits in that code. If that looks okay then it's not Math.random(), so then try substituting the UUID implementation you're using into the uuid() method there and see if you still get good results.
[Update: Just saw Veselin's report about the bug with Math.random() at startup. Since the problem is only at startup, the node-uuid test is unlikely to be useful. I'll comment in more detail on the devoluk.com link.]
Indeed there are collisions, but only under Google Chrome. Check out my experience on the topic in Google Chrome random number generator issue
It seems like collisions only happen on the first few calls of Math.random. Because if you just run the createGUID / testGUIDs method above (which obviously was the first thing I tried), it just works without any collisions whatsoever.
So to make a full test one needs to restart Google Chrome, generate 32 byte, restart Chrome, generate, restart, generate, etc.
Just so that other folks can be aware of this - I was running into a surprisingly large number of apparent collisions using the UUID generation technique mentioned here. These collisions continued even after I switched to seedrandom for my random number generator. That had me tearing my hair out, as you can imagine.
I eventually figured out that the problem was (almost?) exclusively associated with Google's web crawler bots. As soon as I started ignoring requests with "googlebot" in the user-agent field, the collisions disappeared. I'm guessing that they must cache the results of JS scripts in some semi-intelligent way, with the end result that their spidering browser can't be counted on to behave the way that normal browsers do.
Just an FYI.
The answer that originally posted this UUID solution was updated on 2017-06-28:
A good article from Chrome developers discussing the state of Math.random PRNG quality in Chrome, Firefox, and Safari. tl;dr - As of late-2015 it's "pretty good", but not cryptographic quality. To address that issue, here's an updated version of the above solution that uses ES6, the crypto API, and a bit of JS wizardy I can't take credit for:
function uuidv4() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}
console.log(uuidv4());
I just ran a rudimentary test of 100,000 iterations in Chrome using the UUID algorithm you posted, and I didn't get any collisions. Here's a code snippet:
var createGUID = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
var testGUIDs = function(upperlimit) {
alert('Doing collision test on ' + upperlimit + ' GUID creations.');
var i=0, guids=[];
while (i++<upperlimit) {
var guid=createGUID();
if (guids.indexOf(guid)!=-1) {
alert('Collision with ' + guid + ' after ' + i + ' iterations');
}
guids.push(guid);
}
alert(guids.length + ' iterations completed.');
}
testGUIDs(100000);
The answers here deal with "what's causing the issue?" (Chrome Math.random seed issue) but not "how can I avoid it?".
If you are still looking for how to avoid this issue, I wrote this answer a while back as a modified take on Broofa's function to get around this exact problem. It works by offsetting the first 13 hex numbers by a hex portion of the timestamp, meaning that even if Math.random is on the same seed it will still generate a different UUID unless generated at the exact same millisecond.

How can you perform varying base logarithmic functions in Javascript?

This problem is being asked with a node.js server in mind, but I stated the question as "javascript" because I will likely use this same logic for a client-side script, as well.
Here's the problem: given a set of x values, y needs to scale in a logarithmic way. The Math object performs a natural log [ln(x)], but does not provide an interface for specifying the base of the logarithm.
For a specific example, I need to find the following:
log[512](2)
Which should return .1111~
However, I do not see an interface that allows me to accomplish this, nor can I seem to find a library that exposes an option for the log's base. Surely this is a common problem and has a solution, but my searching has only found solutions for different/unrelated problems. Ideas?
You can use the logarithm base change formula:
log[a](n) = log[b](n) / log[b](a)
So in order to get log(2) base 512, use:
function log(b, n) {
return Math.log(n) / Math.log(b);
}
alert(log(2, 512));
Note that Math.log above uses the natural log base; i.e., it would be written as ln mathematically.
I found this answer as a first result in google today, and if anyone else finds it too, there's a small mistake. The correct version is as follows:
function log(b, n) {
return Math.log(n) / Math.log(b);
}

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

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

How to write a prototype for Number.toFixed in JavaScript?

I need to round decimal numbers to six places using JavaScript, but I need to consider legacy browsers so I can't rely on Number.toFixed
The big catch with toExponential, toFixed, and toPrecision is that they are fairly modern constructs not supported in Mozilla until Firefox version 1.5 (although IE supported the methods since version 5.5). While it's mostly safe to use these methods, older browsers WILL break so if you are writing a public program it's recommended you provide your own prototypes to provide functionality for these methods for older browser.
I'm considering using something like
Math.round(N*1000000)/1000000
What is the best method for providing this a prototype to older browsers?
Try this:
if (!Number.prototype.toFixed)
Number.prototype.toFixed = function(precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(this * power)/power);
}
I think Firefox 1.5 and IE 5 are pretty much no longer used, or by a very minor quantity of people.
It is a bit like coding to support Netscape Navigator... :-)
Unless some other major browser (Opera? Safari? unlikely...) doesn't support this, or if your Web logs show lot of legacy browser use, you can probably just use these methods.
Sometime, we have to move on. ^_^
[EDIT] Works fine on Opera 9.50 and Safari 3.1
javascript: var num = 3.1415926535897932384; alert(num.toFixed(7));
The article you reference is a year and half ago, an eternity in IT industry... I think that, unlike IE users, Firefox users often go to the latest version.
From Bytes website, this function is almost the same than Serge llinsky's:
if (!num.toFixed)
{
Number.prototype.toFixed = function(precision)
{
var num = (Math.round(this*Math.pow(10,precision))).toString();
return num.substring(0,num.length-precision) + "." +
num.substring(num.length-precision, num.length);
}
}
Another option is ( which doesn't convert to a string unnecessarily, and also corrects the miscalculation of (162.295).toFixed(2) to 162.29 ( should be 162.30 )).
Number.prototype._toFixed=Number.prototype.toFixed; //Preserves the current function
Number.prototype.toFixed=function(precision){
/* step 1 */ var a=this, pre=Math.pow(10,precision||0);
/* step 2 */ a*=pre; //currently number is 162295.499999
/* step 3 */ a = a._toFixed(2); //sets 2 more digits of precision creating 16230.00
/* step 4 */ a = Math.round(a);
/* step 5 */ a/=pre;
/* step 6 */ return a._toFixed(precision);
}
/*This last step corrects the number of digits from 162.3 ( which is what we get in step 5 to the corrected 162.30. Without it we would get 162.3 */
Edit: Upon trying this specific incarnation, this*=Math.pow(10, precision||0) creates an error invalid left-hand assignment. So gave the this keyword the variable a. It would also help if I closed my functions ^_^;;
Try this:
Number.prototype.toFixed = function(precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(this * power)/power);
}

Categories