Efficient algorithm for equation - javascript

I want to ask about efficient algorithm.
Example i have equation :
x = y + z;
if the value of variable y = 1, variable z = 2 so variable x is 3
But how to get value of y automatically if variable x = 3 and variable z = 2 with that equation? without create new equation y = x - z
I hope can get sample code using C# or javascript.
Another example, if the equation is
a = (((x + y - z)/2)*10)^4
The equation is from program, user submit value of 3 varibles.
User submit variable (x, y, z) or (y, z, a) or (z, a, x) or (a, x, y)
if user input value for var x, y and z, program can displaying value of a with that equation. Without create a = ...
if user input value for var y, z and a, program can displaying value of x with that equation. Without create x = ...
if user input value for var z, a and x, program can displaying value of y with that equation. Without create y = ...
if user input value for var a, x and y, program can displaying value of z with that equation. Without create z = ...

What you are looking for is an 'equation solver'. This is non-trivial and there is quite a bit of research on this and some well-known large mathematical software do this.
For more details, please google 'Algorithms for Computer Algebra'.

You have to resolve the equations with respect to the unknown variable:
x = y + z;
is equivalent to
y = x - z;
and
z = x - y;
For the second equation it is more difficult. If a < 0 there will be no solution. Otherwise you can first take the 4th root:
a = (((x + y - z)/2)*10)^4 <=> sqrt(sqrt(a)) = +/- (x + y + z) * 5
Then resolve it with respect to x, y or z. Note that you will get two solutions in general.
There are programs and libraries that can do these calculations automatically: Check for "symbolic math" or "computer algebra systems".

i sense a deep research of math on that problem you present, you can serach on google about equation algorithm solve that a link of wikipedia
Yes in case you have a simple workflow of some basic algorithm to find a variable
let us suppose this environment;
since there are always going to be three variables, you can valid that only one of the three is null and then select the equation of the variable you want to find if non are null then you send a message that no value are null
The original equation is x=y+z-a
x=5; y=7; z=2; a=null;
If (!x.hasValue ()){
x= y + z - a;
}
....
Else if (!a.hasValue ()){
a = -(x + y + a);
}Else{Console.Write("Don't give value to all variable");}

This isn't how it works. In programming languages you don't really have equations but rather assignments. You can assign a right-side value to the variable on the left side.
So the only way to obtain y, when having x and z is by running
y = x - z
EDIT: you may want to create something like
myFunction(double? x=null, double? y=null, double? z=null, double? a=null)
And then inside you check which variable is null (so not used), and perform your calculations accordingly. You would run it like this
var something = myFunction(x: 1, y: 2, a: 3)

If you don't want to write a new line of code and get the result of 'y' when 'x' is diferent to zero within the same equation, try this ...
// equation : x = y + z
var x=3,y=0,z=2;
x = ((x!=0) ? (x-z) : y ) + z;
console.log("Result : "+ x);
// or saving the value in 'y'
x = ((x!=0) ? y = (x-z) : y ) + z;
console.log("Result 2 : "+ x);

Answering the first question:
Y = X - Z
is the only possible solution. There aren't other ways to calculate Y.
This because computers can't solve equations (or better, they can be programmed to solve them, but only using 'Y = X - Z') , they can change the value of a variable. In this case we set the Y value to (X - Z) value.
Answering the second question:
You can solve that equation doing
X = fourth square of (...)
or you can use libraries that do all this work by themselves, like 'computer algebra system' (Also cited by #FrankPuffer)
Definitely: you can solve the equations doing inverse operation, like 'Y = X - Z', or by using libraries that simplify writing code.

Related

How can I swap two variables without using a temporary variable in Javascript

I know how to swap integers with a temporary variable, like this:
let x = 5;
let y = 7;
x = x + y;
y = x - y
x = x - y;
But how can I swap two variables of any type without using a third variable ?
I just discovered this in Javascript, although it must have been there for decades — and I see the question is asked in lots of languages and the answer in Javascript is unnervingly simple.
[x, y] = [y, x];

How can I offset a global directional force to be applied over a local axis?

I want to apply a forward force in relation to the object's local axis, but the engine I'm using only allows to me apply a force over the global axis.
I have access to the object's global rotation as a quaternion. I'm not familiar with using quats however (generally untrained in advanced maths). Is that sufficient information to offset the applied force along the desired axis? How?
For example, to move forward globally I would do:
this.entity.rigidbody.applyForce(0, 0, 5);
but to keep that force applied along the object's local axis, I need to distribute the applied force in a different way along the axes, based on the object's rotational quat, for example:
w:0.5785385966300964
x:0
y:-0.815654993057251
z:0
I've researched quaternions trying to figure this out, but watching a video on what they are and why they're used hasn't helped me figure out how to actually work with them to even begin to figure out how to apply the offset needed here.
What I've tried so far was sort of a guess on how to do it, but it's wrong:
Math.degrees = function(radians) {
return radians * 180 / Math.PI;
};
//converted this from a python func on wikipedia,
//not sure if it's working properly or not
function convertQuatToEuler(w, x, y, z){
ysqr = y * y;
t0 = 2 * (w * x + y * z);
t1 = 1 - 2 * (x * x + ysqr);
X = Math.degrees(Math.atan2(t0, t1));
t2 = 2 * (w * y - z * x);
t2 = (t2 >= 1) ? 1 : t2;
t2 = (t2 < -1) ? -1 : t2;
Y = Math.degrees(Math.asin(t2));
t3 = 2 * (w * z + x * y);
t4 = 1 - 2 * (ysqr + z * z);
Z = Math.degrees(Math.atan2(t3, t4));
console.log('converted', {w, x, y, z}, 'to', {X, Y, Z});
return {X, Y, Z};
}
function applyGlobalShift(x, y, z, quat) {
var euler = convertQuatToEuler(quat.w, quat.x, quat.y, quat.z);
x = x - euler.X; // total guess
y = y - euler.Y; // total guess
z = z - euler.Z; // total guess
console.log('converted', quat, 'to', [x, y, z]);
return [x, y, z];
}
// represents the entity's current local rotation in space
var quat = {
w:0.6310858726501465,
x:0,
y:-0.7757129669189453,
z:0
}
console.log(applyGlobalShift(-5, 0, 0, quat));
Don't laugh at my terrible guess at how to calculate the offset :P I knew it was not even close but I'm really bad at math
Quaternions are used as a replacement for euler angles. Your approach, thus, defeats their purpose. Instead of trying to use euler angles, levy the properties of a quaternion.
A quaternion has 4 components, 3 vector components and a scalar component.
q = x*i + y*j + z*k + w
A quaternion therefore has a vector part x*i + y*j + z*k and a scalar part w. A vector is thus a quaternion with a zero scalar or real component.
It is important to note that a vector multiplied by a quaternion is another vector. This can be easily proved by using the rules of multiplication of quaternion basis elements (left as an exercise for the reader).
The inverse of a quaternion is simply its conjugate divided by its magnitude. The conjugate of a quaternion w + (x*i + y*j + z*k) is simply w - (x*i + y*j + z*k), and its magnitude is sqrt(x*x + y*y + z*z + w*w).
A rotation of a vector is simply the vector obtained by rotating that vector through an angle about an axis. Rotation quaternions represent such an angle-axis rotation as shown here.
A vector v can be rotated about the axis and through the angle represented by a rotation quaternion q by conjugating v by q. In other words,
v' = q * v * inverse(q)
Where v' is the rotated vector and q * v * inverse(q) is the conjugation operation.
Since the quaternion represents a rotation, it can be reasonably assumed that its magnitude is one, making inverse(q) = q* where q* is the conjugate of q.
On separating q into real part s and vector part u and simplifying the quaternion operation (as beautifully shown here),
v' = 2 * dot(u, v) * u + (s*s - dot(u, u)) * v + 2 * s * cross(u, v)
Where dot returns the dot product of two vectors, and cross returns the cross product of two vectors.
Putting the above into (pseudo)code,
function rotate(v: vector3, q: quaternion4) -> vector3 {
u = vector3(q.x, q.y, q.z)
s = q.w
return 2 * dot(u, v) * u + (s*s - dot(u, u)) * v + 2 * s * cross(u, v)
}
Now that we know how to rotate a vector with a quaternion, we can use the world (global) rotation quaternion to find the corresponding world direction (or axis) for a local direction by conjugating the local direction by the rotation quaternion.
The local forward axis is always given by 0*i + 0*j + 1*k. Therefore, to find the world forward axis for an object, you must conjugate the vector (0, 0, 1) with the world rotation quaternion.
Using the function defined above, the forward axis becomes
forward = rotate(vector3(0, 0, 1), rotationQuaternion)
Now that you have the world forward axis, a force applied along it will simply be a scalar multiple of the world forward axis.

Why does console.log(z) throw NaN?

When it's able to pick up w from the outer scope, why is it not able to pick up z?
var w = 1, z = 2;
function foo( x = w + 1, y = x + 1, z = z + 1 ) {
console.log( x, y, z );
}
foo();
it's able to pick up w from the outer scope
Yes, because you don't have a variable w inside your function.
why is it not able to pick up z?
Because your parameter declares a local variable with the name z, and that shadows the global one. However, the local one is not yet initialised with a value inside the default expression, and throws a ReferenceError on accessing it. It's like the temporal dead zone for let/const,
let z = z + 1;
would throw as well. You should rename your variable to something else to make it work.
The first one works because the w in the w + 1 looks for w in the formal parameters but does not find it and the outer scope is used. Next, The x in the x +1 finds the value for x in formal parameters scope and uses it, so the assignment to y works fine.
In the last case of z + 1, it finds the z as not yet initialized in the formal parameter scope and throws an error before even trying to find it from outer scope.
Changing the variable z to something else as pointed out by #bergi, should do the trick.
var w = 1, z = 2;
function foo( x = w + 1, y = x + 1, a = z + 1 ) {
console.log( x, y, a );
}
foo();
you have
function foo( x = w + 1, y = x + 1, z = z + 1 )
during
x=w+1
x is undfined
and then w is undefined also
so it look into local execution context didnt find any value
so it goes outerscope and find w=1
so in local space w also become 1
now during
z = z + 1
the z which is at the left side of = is undefine
and then the z which is at the right side of = also undifine so it looks for
z inside local execution context and find one the z which was at the left side
of the equation so it do not need to go to outer space.
so z become undifine
however if you write this way z=this.z+1 you will get z= 3
cause this.z wont look into localscope directly go to outerscope and find z=2

Quadratic function for increment speedup of countup

I'm writing a jQuery plugin for fast-counting up to a value when a page loads. Since javascript can't run as fast as I want it to for larger numbers, I want to increase the increment step so that it completes within a given timeframe, so I'd need a quadratic function that passes through origo and has it's turning point at y = target counting value and x = target duration, but I can't get a grip on the math for doing this. Since both the number and the duration can change, I need to be able to calculate it in javascript aswell.
Hopefully someone can help me with this one!
Let's formalize the statement a bit.
We seek an equation of the form
y = a*x*x + b*x + c
where x is the time axis and y is a count axis. We know that one point on the curve is (0,0) and another point is (xf, yf) where xf is the final time and yf is the target count. Further, you wish for the derivative of this equation to be zero at (xf, yf).
y' = 2*a*x + b
So I have three equations and three unknowns:
(0,0) => 0 = c
(xf, yf) => yf = a*xf*xf + b*xf + c
y' = 0 # (xf, yf) => 0 = 2*a*xf + b
You should be able to solve it from there.
// Create a quadratic function that passes through origo and has a given extremum.
// x and y are the coordinates for the extremum.
// Returns a function that takes a number and returns a number.
var quadratic = function (x, y) {
var a = - (y / (x * x));
var b = (2 * y) / x;
return function (x) {
return a * x * x + b * x;
};
};

Math: 3 rotating dials with 3 values that should always = 100%

I have three dials: D1, D2 and D3. Together their values should always be 100% and their default Values are 50%, 25% and 25% respectively.
When a user edits D2 or D3, D1 should act as the FIRST pot to pull from and Deposit to.
Here is the problem: what if the editable dials are increased past the point of D1 reserves? I need to find a way to have the the remaining pull from the dial not being edited at that moment.
I guess I am looking for a elegant solution as opposed to a hack. Any one got such a solution?
http://jsfiddle.net/cborgia/ByWCA/
What you are trying to do is solve an equation of three functions like:
X + Y + Z = K;
where:
X = x + a(dx)
Y = y + b(dy)
Z = z + c(dz)
K = 100
and
a, b and c are functions
x, y and z are the current values of the knobs and
dx, dy and dz are the changes in knob values
The functions are solved given values for K (always 100) and one of X, Y and Z where X, Y and Z are in the range 0 to 100 inclusive.
You don't say what should happen as X, Y and Z approach 0 or 100 - are they proportionally reduced, or is the excess or deficit applied to the other non–user adjusted knob?

Categories