trig functions with imaginary numbers in javascript - javascript

I am trying to write some code in javascript to calculate trig functions, inverse trig functions, and hyperbolic trig functions with imaginary numbers. I have the sin, cos, sinh, and cosh working well. However, I am having some trouble getting my solutions for others to match the only verification that I can find at this site.
For example, below is the code for asin(x+yi). I am using the formula located here along with the definitions for modulus and argument found there as well. It has no errors, but doesn't match the results from the site I cited. What am I doing wrong?
asin(z)=-i*ln(iz+sqrt(1-z^2))
var id1=SquareComplex (window[id].Solution_real, window[id].Solution_imag);
var real=1-window[id1].Solution_real;
var imag=window[id1].Solution_imag;
var id2=SquareRoot(real, imag);
imag=window[id].Solution_real+window[id2].Solution_imag;
real=-window[id].Solution_imag+window[id2].Solution_real;
var modulus=Math.sqrt(real^2+imag^2);
var argument=Math.atan2(imag,real);
var Solution_imag=-Math.log(modulus);
var Solution_real=argument;
This code is intended to work in several steps. The first line calls a function that squares the complex number z. The second and third lines subtract the result from the number 1. The fourth line calls a function to take the square root of the complex number. The fifth and sixth lines add the results of the previous actions to the result of multiplying the complex number by i. The remaining lines get the modulus and argument of those results, take the natural logarithm, and multiply it by a negative i.

Your first three lines are:
var id1=SquareComplex (window[id].Solution_real, window[id].Solution_imag);
var real=1-window[id1].Solution_real;
var imag=window[id1].Solution_imag;
assuming that id is your initial z then this is not calculating the real and imaginary parts of 1-z^2 as I believe it is indtended to. The reason being that the imaginary part isn't being subtracted.
Try it with
var imag = -window[id1].Solution_imag;
and see if that helps. I can't guarantee there aren't any more errors in it but I'd suggest just going through and being really careful about making sure each line does what it should.

You may be interested in math.js, which comes with support for complex numbers for all functions including trigonometry:
var value = math.complex(2, 3);
var ans = math.asin(value);
Or using the expression parser:
var ans = math.eval('asin(2 + 3i)');

Related

Calculate speed from velocity vector using box2d GetLinearVelocity();

I need to find the speed of an object in a game. The game is made in HTML5 with jquery and jquery.box2d.
For this I can use these methods:
GetLinearVelocity().x;
GetLinearVelocity().y;
I'm then trying to calculate the speed from this piece of code, but get some values that doesn't make sense when I console.log it. This is my code:
var heroVelX = game.currentHero.GetLinearVelocity().x;
var heroVelY = game.currentHero.GetLinearVelocity().y;
var speed = Math.sqrt(heroVelX^2 + heroVelY^2);
console.log(speed);
Some of the values in console.log are numbers, but most of them are NaN (Not-A-Number), which confuses me? Can someone help me solve this?
The goal I want to achieve, is to see when the speed(of object .currenHero) drop below a certain value, so I can excute a new state in the game.
Your problem is that you're using the wrong operator (Bitwise XOR) for doing square - see here.
What you need to do is:
var speed = Math.sqrt(Math.pow(heroVelX, 2) + Math.pow(heroVelY, 2));
The only time the square root function should return NaN is when the value being square rooted is negative. A way to go about testing if this is the issue would be to try squaring the values in a different line of code before square rooting them.
heroVelX = (heroVelX) * (heroVelX)
Another way to potentially shine some light on the problem would be to add log statements printing out the values of the velocities and the velocities squared before square rooting.

Seed-based world generation using sin

I'm tried to make some world generation mechanism using Math.random() whenever I needed something random, but then decided that I wanted it seed-based, so, given a seed, I changed all of the Math.random() to Math.sin(seed++)/2+0.5, hoping it would do the same thing, but would be the same if the seed was the same seed.
Then someone made me notice that the sin wave hasn't got even distribution, and finally I saw why some of my code was working strangely.
I was wondering if there was a simple fix, or if there isn't, another very simple seed based randomizer like this
So, I looked at your method, t1wc, and I found that it isn't actually evenly distributed. It is significantly more likely to spit out numbers near 0 or near 1 than it is to spit out numbers near 0.5, for example. This is just a consequence of the way that the sine function works.
Instead, you might try using a method called Blum Blum Shub (named after the authors of the original paper, wonderfully). It is evenly distributed and quite fast. Given a seed, it works as follows:
Square the seed and put the result in a temporary variable (x).
Take the mod of x base M.
M is a product of two large primes.
The value of x is a new seed to be used for future calculations.
Return x/M as your pseudo-random number. It will be evenly distributed between 0 and 1.
Below is a simple implementation of a Blum Blum Shub:
var SeededRand = function(seed, mod1, mod2)
{
return function()
{
seed = (seed*seed) % (mod1*mod2);
return seed/(mod1*mod2);
};
};
If you want to make a new random number generator, you just call:
var rand = SeededRand(seed, mod1, mod2);
Where seed is some initial seed (1234567890 works well), and mod1 and mod2 are some large primes (7247 and 7823 work well). rand is just a variable that I've defined to hold the output.
Now, to start getting random values, you just call:
rand();
Which will spit out a different value each time you run it.
If you have any questions, please ask!
There is a very nice seed-based randomizing script already made. It can be found here.
ok guys, found out this is what I'm really looking for:
(((Math.sin(seed.value++)/2+0.5)*10000)%100)/100
It sends out even spreaded numbers, and I guess it's a lot simpler than any other number generator I've seen

simplifying the contents of an input using the javascript math system

This obviuosly works perfectly:<script>alert(5*8-4)</script>
but i need to solve whatever someone puts inside an input box.
Heres what I thought of doing: I would get the value of the input, into a variable. then I would use
document.write("<script>alert("+theinputvalue+")<script>");
or do this:
var string="<script>alert("+theinputvalue+")<script>";document.write(string);
but nothing works.
Is it even possible to do this? if not, tell my what simple other system I could use.
eventually, I will use it to graph lines like this:
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d")
for(var x=-100; x<100; x=x+.2){
y = .1*(x*x)
ctx.fillRect(x+50, -1*y+50, 2, 2);
}
http://jsfiddle.net/KGgq4/
eval('5*8-4')
will result in 36
I'm not aware of any library that is doing that (this doesn't mean that there are no such it simply means I never actually needed that) but what you should end up doing is to build an automata that will parse input string and transform it to a proper graph with proper transformations. This is not very easy topic and if you want to go this route you should start reading on arithmetic expressions parsing algorithms (sorry I do not have any solution in place).
Or you can cheat and define types of equations that will be selected by user. Once user selects type of equation you should be able show user inputs where user will be able to select coefficients. You can read those coefficients into different variables and apply transformations in your draw procedure (For example if user will select type sin(x) you know that general equation has following formula: y = k*sin(a*x + b) + c. So once it is selected you can allow user to enter k, a, b, c and based on that input calculate appropriate locations of points for your graph.)
Well, third solution could involve "eval ", but usually you should avoid eval at any cost (B/c it is straight forward JavaScript injection which may be an OK for this case but may get you in trouble later in your life. ).
You can use math.js, which comes with an advanced expression parser. It supports definition of variables and functions.
// create an instance of math.js
var math = mathjs();
// evaluate an expression
math.eval('5*8-4'); // 36
// user defined function (returns a native JavaScript function)
var f = math.eval('f(x) = 2*x^2 + 6');
// use the function (for graphing or something)
f(2); // 14

Javascript: Solve a system of equations

I'm making a dew point calculator using the "closer approximation" on wikipedia.
I want to be able to calculate the dew point if the user enters any two variables.
Is there an easy way to do this rather than having a lot of if-statements?
More specifically: What if I wanted to use the wet-bulb temperature instead of the relative humidity? Would I have to make a new function or use an if-statement to exclude a set of variables?
Currently I'm using the temperature and relative humidity:
$('#calculate').click(function(){
//Get Temp
var T = parseInt($('#val1').val());
//Get RH
var RH = parseInt($('#val2').val());
//Get es and ex
var es = 6.112*Math.exp(17.76*T/(T+243.5));
var ex = (RH*es)/100;
//Calculate Dew Point
var Tdp = (243.5*Math.log(ex/6.112))/(17.67-Math.log(ex/6.112));
$('#output').append("<p>Dew Point"+Tdp+"</p>");
});
FYI solving systems of nonlinear equations is generally a hard problem. Do whatever you can to avoid that.
My usual approach if multiple pairs of values can be used to calculate an answer is to use the pair of values I'm given to calculate a canonical pair of values, which then is used to do the real calculation. Furthermore since it gets messy to have to sort through input to figure out what you have been given so you can DWIM, it might make sense to have separate functions for each pair of inputs that I'll accept. (Or it might not depending on the flow of control in your program, you know that better than I do.)

What are the chances that JavaScript Math.Random() will create the same number twice in a row?

Is this correct? using - http://en.wikipedia.org/wiki/Binomial_probability
Looks like values are from .0000000000000000 to .9999999999999999
Probability of happening twice = p^2 = (1/9999999999999999)^2 = 1.0 e-32
I think I am missing something here?
Also, how does being a pseudo random number generator change this calculation?
Thank You.
In an ideal world Math.random() would be absolutely random, with one output being completely independent from another, which (assuming p=the probability of any given number being produced) results in a probably of p^2 for any value being repeated immediately after another (as others have already said).
In practice people want Math.random to be fast which means pseudo-random number generators are used by the engines. There are many different kinds of PRNG but the most basic is a linear congruential generator, which is basically a function along the lines of:
s(n + 1) = some_prime * s(n) + some_value mod some_other_prime
If such a generator is used then you won't see a value repeated until you've called random() some_other_prime times. You're guaranteed of that.
Relatively recently however it's become apparent that this kind of behaviour (coupled with seeding the PRNGs with the current time) could be used for some forms tracking have led to browsers doing a number of things that mean you can't assume anything about subsequent random() calls.
I think the probability of getting two numbers in a row is 1 divided by the range of the generator, assuming that it has a good distribution.
The reason for this is that the first number can be anything, and the second number needs to just be that number again, which means we don't care about the first number at all. The probability of getting the same number twice in a row is the same as the probability of getting any particular number once.
Getting some particular number twice in a row, e.g. two 0.5s in a row, would be p^2; however, if you just care about any number twice in a row, it's just p.
If the numbers were truly random, you'd expect them, indeed, to appear with probability 1/p, so twice that would be 1/p^2.
The value for p is not exactly the one you have though, because the numbers are being represented internally as binary. Figure out how many bits of mantissa the numbers have in javascript and use that for your combinatoric count.
The "pseudorandom" part is more interesting, because the properties of pseudorandom number generators vary. Knuth does some lovely work with that in Seminumerical Algorithms, but basically most usual PN generators have at least some spectral distributiuon. Cryptograp0hic PN generators are generally stronger.
Update: The amount of time shouldn't be significant. Whether it's a millisecond or a year, as long as you don't update the state The probabilities will stay the same.
The probability that you would get 2 given numbers is (1/p)^2, but the probability that you get 2 of same numbers (any) is 1/p. That is because the first number can be anything, and the second just needs to match that.
You can kind of find out, just let it run a few days :)
var last = 0.1;
var count = 0 | 0;
function rand(){
++count;
var num = Math.random();
if(num === last){
console.log('count: '+count+' num: '+num);
}
last = num;
}
while(true) rand();

Categories