javascript typeof / NaN confusion - javascript

So I'm making a small game using the canvas API and and I'm fairly new to Javascript. But while I was working on making the charecter be able to shoot in a full 360 degrees I came across a error in the code below (this function should return the angle between the mouse position and player position nothing else)
calculateAngle : function(x,y){
var opp = 0; //opposite
var adj = 0; //adjecent
var rad = 0; //radian
var ang = 0; //angle
//side lengths
var x1 = gfx.player_center_x //the player x position
var x2 = mouse_x; //the mouse x position
var y1 = gfx.player_center_y; //the player y position
var y2 = mouse_y; //the mouse y position
//find 2 lengths of the triangle
opp = (y2 - y1);
adj = (x2 - x1);
//find the missing angle between the adjecent and hypotenuse
rad = Math.atan2(adj, opp);
ang = rad * 180 / Math.PI;
//-------------------------//
console.log(ang); //prints: NaN
console.log(typeof ang); //prints: number
//------------------------//
return ang;
}
When executed its returns NaN but ang is a number!
Why does javascript think the variable ang not a number? Its declared as 0 which typeof returns number, please help!
UPDATE: Careless error made, x1 and y1 ect changed location and I forgot to implement it, thanks for you answers though

NaN is a special value. Internally it's a number, but it's a specific value that's given the special meaning of "this value is mathematically undefined". Any operation that results in an undefined number (such as 0/0) results in NaN, but it's still a number! Just not a defined number.
Math.atan2 is implemented in such a way that it cannot return NaN (because it handles the "edge cases" where y/x would be Infinity - another "number" that isn't a defined number) so it seems almost certain that your NaN is coming from the calculation of opp and/or adj. You should log these values and see what's up.

NaN is a IEEE 754 “Not-a-Number” value. In javascript it belongs to the number type even it is known as NaN(Not a Number). It's a quirks of javascript. Even according to
IEEE Standard for Floating-Point Arithmetic (IEEE 754):
arithmetic formats: sets of binary and decimal floating-point data, which consist of finite numbers (including signed zeros and subnormal numbers), infinities, and special "not a number" values (NaNs).

Related

How to find the negative inverse of a number?

I have two points A and B and a population of points, and I would like to find the distance from each and every point to the line AB.
I first get the slope of the line, and then its Y intercept. And following Distance between point & line, at second 00:48 it states that we need the negative inverse of the slope (number).
I would like a function that takes any number, and returns the negative inverse of it. Something like let inverseOfSlope = getInverse(slope); Please and thanks
getDistance(PointA: Object, PointB: Object, Target: Object)
{
// find slope of the line
let slope = (PointA.y - PointB.y) / (PointA.x - PointB.x)
// find y intercept
let yIntercept = PointA.y + ((-1 * slope) * PointA.x)
// find inverse negative of the slope
let newSlope = -1 * getInverse(slope);
// find new y-intercept
let NewYintercept = PointA.y + ((-1 * newSlope) * PointA.x)
// get point of intersection between the two lines
// by solving the two equations equal to each other
// calculate distance between target and point of intersection
// easy
// return result
}
As 4castle comments "the negative inverse of a number" is a trivial thing with no apparent relevance to your problem. Wikipedia gives the formula you need to compute the distance from a point (x0, y0) to a line defined by two points (x1, y1) and (x2, y2), and that formula is straightforwardly implemented in any language without any need for your getInverse(slope) function.

How to get the finest possible precision in JavaScript?

I'm trying to determine the smallest possible non-negative, non-zero value available in a JavaScript number for addition and subtraction. If necessary then the smallest possible number for addition and subtraction per a given value (i.e. if the "smallest value" differs between numbers at a given range I'd like to find the smallest value for a given number or range of numbers, or the next number greater or smaller than a given number would also work.)
As an example to underline why I'm looking for this, please see this fiddle or the code below. It simply scales a rectangle by area, given both the starting width/height and ending width/height the values should be in whole numbers. It works as outlined below for the given example however I'm fairly sure the fudge-factor of 0.000000000000002 won't scale to any possible set of values. I understand the overwhelming majority of solutions in the floating point range of possible values will not be whole numbers and that many will likely even extend beyond the JavaScript number's level of precision or simply be unable to be represented in it, however given the check below for greater than or less than based on ration and/or area I have a high degree of confidence that if I can find the smallest possible value which the result can be offset I can at least hit the number most computationally accurate for a given input, which would be the objective here.
console.clear();
var w = 3;
var h = 5;
var a = w * h;
var r = w / h;
console.log(w, h, a, r);
var t = 240;
var w2 = Math.sqrt(t);
var h2 = w2;
w2 = w2 * r / Math.sqrt(r);
h2 = h2 / r * Math.sqrt(r);
var r2 = w2 / h2;
var m = 10;
var a2 = w2 * h2;
console.log(w2, h2, a2, r2);
while ((r2 > r) && (m > 0)) {
h2 += 0.000000000000002;
r2 = w2 / h2;
m--;
}
m = 10;
while ((r2 < r) && (m > 0)) {
h2 -= 0.000000000000002;
r2 = w2 / h2;
m--;
}
var a2 = w2 * h2;
console.log(w2, h2, a2, r2);
Output:
Console was cleared
3 5 15 0.6
12 20.000000000000004 240.00000000000006 0.5999999999999999
12 20 240 0.6
The smallest possible number can be interpreted in several ways. For the sake of usefulness to others I will post information about all three interpretations, although I believe you are looking for the first one:
If you mean in terms of precision - the smallest possible number closest to zero:
Number.MIN_VALUE
would give you: 5e-324
If instead you mean the smallest possible floating point number, which would include negative numbers, then you'd be looking for:
- Number.MAX_VALUE
Note the minus sign there. That would give you: -1.7976931348623157e+308.
And the third interpretation is the difference between 1 and the smallest floating point number greater than 1, also known as the Machine Epsilon, in which case you can use:
Number.EPSILON
Which would give you: -2.220446049250313e-16.
As a final note, the examples may be inaccurate if you are running on a CPU that supports different floating point storage scheme, like a 32bit CPU for example.

Floating point number precision or algorithmic error in JavaScript

I tried to implement in JavaScript rotation around point, using rotation matrix, but for some reason I got some unexpected results - instead of moving around a point, my figure was moving along a line. Here I provide completely reproducible example, which demonstrates that after rotation distance between a rotating point and the center changes. Here it is:
var alpha = 0.10146071845187077;
var cos_ = Math.cos(alpha);
var sin_ = Math.sin(alpha);
var center = [4861165.687852355,7606554.432771027];
var pointBefore = [4847712.770874163, 7610682.032298427];
var dist1, dist2, x1, y1, x2, y2, pointAfter = [];
// 1. substract + 2. rotate + 3. get back
// 1.
x1 = pointBefore[0] - center[0];
y1 = pointBefore[1] - center[1];
// 2.
x2 = cos_ * x1 - sin_ * y1;
y2 = sin_ * x1 + cos_ * y1;
// 3.
pointAfter[0] = x2 + center[0];
pointAfter[1] = y2 + center[1];
// Check distances
dist1 = Math.sqrt(Math.pow(x1, 2) + Math.pow(y1, 2));
dist2 = Math.sqrt(Math.pow(pointAfter[0] - center[0], 2) +
Math.pow(pointAfter[1] - center[1], 2));
console.log(JSON.stringify({dist1: dist1, dist2: dist2}));
// -> {"dist1":14071.888753138577,"dist2":14071.88875313881}
I hope, I made some errors in math, but I cannot see them.
Inaccuracy is due to the fact how floating point numbers are stored:
Is floating point math broken?
Basically, it's impossible to store irrational numbers and high precision real numbers in the fixed space of 64bits so there will be rounding errors which become significant after many operations. Think of the number 2/3, you cannot represent it accurately no matter the precision.
A possible solution is to either calculate with whole numbers only when possible or round the results after each operation.

Get NaN in Math.pow operation with second parameter as a decimal value

I have a equation with a square with root=5:
(source: xpg.com.br)
I need to write this equation in javascript so:
var y = Math.pow(-x, 1 / 5); // or Math.pow(-x, 0.2);
So far, so good.
But when i try the value x = 400.
var y = Math.pow(-400, 0.2);
I'm aways get NaN, but this equation returns a Real value.
If I use my calc or google or any other calc I get something like:
(-400) ^ 0.2 = -3.31445401734
And this is correct. But the javascript is screwing up with me.
Any one can tell me why and/or how to fix it?
This is according to the ECMAScript Specification section 15.8.2.13:
pow (x, y)
If x < 0 and x is finite and y is finite and y is not an integer, the
result is NaN.
In our case x is finite and is less than 0, while y is a finite float number.
REF: http://www.ecma-international.org/ecma-262/5.1/#sec-15.8.2.13
You can use the fact
y = (-x) ^ (1/5)
= (-1) ^ (1/5) * x ^ (1/5)
= -1 * x ^ (1/5)
To simplify your problem to
-Math.pow(400, 0.2);
Which won't cause errors

Javascript function for trilinear interpolation

All,
I THINK that I'm looking for a function for Trilinear interpolation.
Here's the details:
I have a three dimensional dataset:
Dimension 1 varies from 0 to 100 in increments of 5
Dimension 2 varies from 0 to 100 in increments of 5
Dimension 3 varies from 0 to 1 in increments of 0.1
So, I have 4851 total values (21 x 21 x 11).
If I need to find the value for (10, 25, 0.3) - that's easy - I can just look it up in the 3-dimensional array.
But, I need to be able to come up with the best approximation, given dimensional values of (17,48,0.73), for example.
So, I think that what I'm looking for is a trilinear interpolation (although I'd definitely appreciate any suggestions for a better method, or a hint that I'm on the wrong topic altogether...)
A quick google search turns up this formula:
Vxyz =
V000(1-x)(1-y)(1-z) +
V100x(1-y)(1-z) +
V010(1-x)y(1-z) +
V001(1-x)(1-y)z +
V101x(1-y)z +
V011(1-x)yz +
V110xy(1-z) +
V111xyz
Which looks like what I'm looking for, but I'm not sure what x, y, and z represent. If I had to guess, x is a ratio - the distance of my "target" first dimension value from the nearest two values I have, y is the ratio for the second dimension, and z is the ratio for the third dimension.
Of course, since I don't really know what I'm talking about, I wouldn't know if this is right or wrong.
So, ideally, I'd like a bit of Javascript or pseudo-code that shows exactly how to accomplish this.
Many thanks in advance!
The code you are looking at is trying to do a weighted average of the 8 points of the cube with vertices that are in your dataset, and which encloses the point you are trying to find a value for.
For a point p
// Find the x, y and z values of the
// 8 vertices of the cube that surrounds the point
x0 = Math.floor(p.x / 5);
x1 = Math.floor(p.x / 5) + 1;
y0 = Math.floor(p.y / 5);
y1 = Math.floor(p.y / 5) + 1;
z0 = Math.floor(p.z / .1);
z1 = Math.floor(p.z / .1) + 1;
// Look up the values of the 8 points surrounding the cube
p000 = dataset[x0][y0][z0];
p001 = dataset[x0][y0][z1];
// ...
// Find the weights for each dimension
x = (x - x0) / 5;
y = (y - y0) / 5;
z = (z - z0) / .1;
// Compute the guess using the method you found
// ...

Categories

Resources