Box Muller Transform is leaning to the right - netlogo

I am building a computational simulation (Netlogo) of the spread of disinformation.
For a start, I want to distribute the political preference of the population following a basic Gaussian distribution (later on I can adjust the distribution to my liking).
I know that the Box Muller Transform is the easiest way to do this.
However, when implementing it, I find that the plot always has a tendency to lean to the right.
Does someone know why this is and how I can prevent it?
Also, y2 gives a very different plot than y1. When looking it examples of Box Muller, they all show two plots with similar Gaussian distribution. Does someone also know the reason for this doesn't happen with my code?
I used the following code:
let u1 random-float 1
let u2 random-float 1
let z1 sqrt (-2 * ln u1) * cos (2 * pi * u2)
let z2 sqrt (-2 * ln u1) * sin (2 * pi * u2)
report z1
random-float 1 means it will pick a floating point number between 0 and 1.
Thanks in advance!

NetLogo uses degrees for angles and I think that form is for radians. But this is all unnecessarily complicated if all you want to do is draw from a normal distribution, there is a random-normal function

Related

Is there any numerical-accurracy difference on calculating sin(pi/2-A) and cos(A) in Matlab?

I am reading a matlab function for calculating great circle distance written by my senior collegue.
The distance between two points on the earth surface should be calculated using this formula:
d = r * arccos[(sin(lat1) * sin(lat2)) + cos(lat1) * cos(lat2) * cos(long2 – long1)]
However, the script has the code like this:
dist = (acos(cos(pi/180*(90-lat2)).*cos(pi/180*(90-lat1))+sin(pi/180*(90-lat2)).*sin(pi/180*(90-lat1)).*cos(pi/180*(diff_long)))) .* r_local;
(-180 < long1,long2 <= 180, -90 < lat1,lat2 <= 90)
Why are sin(pi/2-A) and cos(pi/2-A) used to replace cos(A) and sin(A)?
Doesn't it introduced more error source by using the constant pi?
Since lat1, lat2 might be very close to zero in my work, is this a trick on the numerical accuracy of MATLAB's sin() and cos() function?
Look forward to answers that explain how trigonometric functions in MATLAB work and analyze the error of these functions when the argument is close or equal to 0 and pi/2.
If the purpose is to increase accuracy, this seems a very poor idea. When the angle is small, 90-A spoils any accuracy. That even makes tiny angles vanish (90-ε=90).
On the opposite, the sine of tiny angles is very close to the angle itself (radians) and for this reason quite accurately computed, while the cosine is virtually 1 or 1-A²/2. For top accuracy on tiny angles, you may resort to the versine, using versin(A):= 1-cos(A) = 2 sin²(A/2) and rework the equations in terms of 1-versin(A) instead of cos(A).
If the angle is close to 90°, accuracy is lost anyway, 90°-A will not restore it.
I very much doubt this has to do with accuracy. Or at least, I don't think this helps any when it comes to accuracy.
The maximum difference between both sin(pi/2-A) - cos(A) and cos(pi/2-A) - sin(A) is 1.1102e-16, which is very small. This is just basic floating point accuracy, and there's really no way of telling which of the numbers is more correct. Note that cos(pi/2) = 6.1232e-17. So, if theta = 0, your colleague's code cos(pi/2-0) will give an error of 6.1232e-17, while simply doing the obvious sin(0) will be correct.
If you need numbers that are more accurate than this then you can try vpa.
I guess this is either because your colleague found another formula and implemented that, or he/she's confused and has attempted to increase the accuracy.
The latter might be the case if he/she tried to avoid the approximations sin(theta) ≈ theta and cos(theta) ≈ 1 for small values of theta. However, this doesn't make sense, since cos(pi/2-theta) ≈ theta and sin(pi/2-theta) ≈ 1 for small values of theta.
Best chance is to ask directly to the author of the text where you got those expressions from, if possible indeed.
It may be the case that the original expressions come from navigation formulae that were written when calculations were done manually: pencil paper ruler, no computers, no calculators.
Tables and graphs were then used to speed up results: pi-x was equivalent to start read table from other side or read graph upside-down.

Is there a way to code a multivariate normal distribution in NetLogo

I want to sample from a multivariate normal distribution for a model in netlogo. I know there's a random-normal function but I'd like to extend this to two dimensions.
Or am I better off coding it up in R and feeding it to the netlogo model that way?
Okay, it's been a long time since I had to do something like this. But you want something like (with rho as your correlation that you control):
set dim1 random-normal 1 0.2
set dim2 rho * dim1 + sqrt(1 - rho ^ 2) * random-normal 5 1
You might want to check on crossvalidated (the statistics equivalent to stackoverflow) to get the correct formula. But it's definitely straightforward to do in NetLogo once you know how to adjust a normal random number to introduce the dependency. Using the R extension is always fiddly and it's not worth the effort if this is all you are doing with it.

Rotation to obtain coordinate in Netlogo

I trying to implement the below answer by Yves Daoust.
https://math.stackexchange.com/questions/1065013/rotation-to-obtain-corodinate
Code
to-report calx2 [x0 y0 x1 y1 A]
report x0 + (y1 - y0) * tan ( A + atan (y1 - y0) (x1 - x0))
end
I don't seem to get intended output(can't figure the mistake from o/p testing). Where am going wrong? It seems I have some problem in how to implementing atan in NetLogo considering the axes are according to turtle.
Please point the error if possible.
Also, are there any easier ways to accomplish the same in NetLogo.
I get the mistake it should atan x y. As I was inverse it two times as the answered question already considered the angle A with vertical axis ,that is, NetLogo's axis style.

finding location of a point along the arc distance in matlab

I have a parabola y=a*(x-alpha)*(x-beta) where a, alpha, beta are known
let x1,y1 be initial points on the above parabola. I now have to cover a distance D along the arc from the initial point. The aim is to get the final position on the parabola after covering the required Arc distance.
One method is to keep checking from initial position to end point of parabola and check whether the integral is equal to the required distance. But this algorithm takes ages to complete as I need to do this many times.
Is there a faster way to do this ?
OK, a line distance on a parabola is not obtained by integration per se. I replaced your a with \gamma for convenience.
y = gamma(x-alpha)(x-beta) -> gamma*x^2 + (-gamma*alpha - gamma*beta)*x + alpha*beta*gamma
Substitute:
a = gamma
b = -gamma*alpha - gamma*beta
c = alpha*beta*gamma
So one can write:
y = a*x^2 + b*x + c
From this formula (parabola) the focal point f is determined by:
f = (1-D)/(4*a) - (-D)/(4*a)
In which
D = b^2 - 4*a*c
Now first define p as the perpendicular distance from a location on the curve to the vertical axis of symmetry x_p:
p = -b / (2*a) - x_p;
From this the arc length is calculated by:
h = p/2
q = sqrt(f^2+h^2)
s = h*q/f + f* ln (h*q/f)
In which s is the paramatric representations of your curve. The length of a curve is found by using two points s and then the distance between those points, so:
Distance = s_1 - s_2 = (h_1*q_1/f + f * ln (h_1*q_1/f)) - (h_2*q_2/f + f * ln (h_2*q_2/f))
With some simplifications:
Distance = (h_1*q_1 - h_2*q_2)/f + f* ln (( h_1 + q_1) / (h_2 + q_2))
To implement it fully in MatLab is up to you for now. Let me know if you run into any problems.
Good luck and have fun!
This is a nonlinear equation: you are given x1,y1 and seek x2, y2. x2 and y2 must satisfy the parabola equation and they must satisfy the arclength equation along a curve. http://en.wikibooks.org/wiki/Calculus/Arc_length
So that integral gives you the second equation. Now you have two equations and two unknowns - look up matlab fsolve http://www.mathworks.se/help/optim/ug/fsolve.html
assume the integral can't solve analytically (Can it?) then just solve it numerically using integrate - should still be much faster than just brute force search...
If you need to do this many times, make sure that the previous solutions are given as initial guesses for the next fsolve / integrate calls
I have no idea what are you using this for. But let me try to help you anyway
Well, this problem is not so hard to solve anallitically. I mean, it's just a simple line integral of 1 over a parabole. And good for you, it's been done before. http://en.wikipedia.org/wiki/Arc_length#Length_of_an_arc_of_a_parabola
All you need to do is to find the symmetry axis, not hard, X = (alpha + beta)/2, and the focus length (a little bit trickier, but if you google that I'm sure you'll find it). And I found it for you. https://math.stackexchange.com/questions/574688/what-is-the-focal-width-of-a-parabola shows the canonical form of the parabole, so all you need to do is to factor your equation (http://www.math-prof.com/Alg2/Alg2_Ch_40.asp)
Now the equation you need to solve is not pretty. Put everything in terms of p and let MatLab solve it for you (it shouldn't take forever).

Solve nonlinear equation in matlab

I need to know how to solve a system of nonlinear equations but varying a parameter, so that every time you change that parameter will throw me the result of that system (need all results), I thought a for, which is changing the parameter, solve the equation and each result is stored in a spreadsheet, the problem is that as you can not solve the system and as a result I throw and nonsymbolic numerical values​​, they give you an example of the system that must be solved:
0 = 125 +100 * cos (x) -25 * cos (a) -175 * cos (y)
0 = 100 * sin (x) -25 * sin (a) -175 * sin (y)
In the parameter to be changed is a and going to go keeping the corresponding values ​​of x and y in the spreadsheet.
You need to know how to solve non-linear equations. That means picking a starting point, creating an incremental, iterative solution, and providing tolerances for stopping. You need to know that not every non-linear equation has a solution. Your choice of starting point and iterative strategy might have a profound influence on whether or not you can find a solution and the efficiency of the process.
What are you solving for here? You have two equations; I'll assume two unknowns (x, y).
You need more basic information before you can use a tool like Matlab. It might encapsulate a lot of the details for you, but it won't make algorithm choices for you. You still have to know something, especially about your system of equations.
Start by reading stuff like this:
http://www.physicsforums.com/archive/index.php/t-106606.html
I'd recommend plotting your equations over a range of x and y. You should know what the terrain looks like before you start. You're dealing with trig functions, so x and y vary from zero to 2π and then repeat. Plot a few periods of x and y and see what you get back.
You can use Matlab's symbolic solver if you have the Symbolic toolbox...
syms x y a
b(1) = 100 * sin (x) -25 * sin (a) -175 * sin (y)
b(2) = 125 +100 * cos (x) -25 * cos (a) -175 * cos (y)
z = solve(b,x,y)
Xsoln = simplify(z.x)
Ysoln = simplify(z.y)
where Xsoln and Ysoln denote the solutions written in terms of the value of a. You can then evaluate the solutions at multiple values of a by either doing
aval = 0.5; % or whatever value you want
subs(Xsoln,a,aval)
or by converting the solution to a function handle and evaluating it that way (this is the preferred approach if you need to evaluate at many points):
xf = matlabFunction(Xsoln)
xf(0.5)