newton square root algorithm condition confusion? - algorithm

the algorithm is pretty straight forward I implemented it as soon as I saw newtons equation
function sq(x , e , g ){
g = g || x / 2
if(Math.abs( g * g - x ) < e )
return g
else
return sq( x , e , ( g + x / g ) / 2 )
}
now here is the thing on really small values the algorithm gives a way off answer and on really large values the algorithm exceeds the call stack .
I understand why
what I don't understand is in the first condition ..
if(Math.abs(g*g -x) < e ) why!! if we divide by x before comparing solves the problem e.g:
if(Math.abs(g*g -x) / x < e)
function sq(x , e , g ){
g = g || x / 2
if(Math.abs( g * g - x ) / x < e )
return g
else
return sq( x , e , ( g + x / g ) / 2 )
}
call the function like this first arg is the number you wanna compute the square root of , second is epsilon which is the range is which when I get a value should be acceptable , you could define an initial guess as a third argument
e.g:
sq( 9 , 0.01)
or:
sq(9 , 0.01 , 2)

Typically, you would specify ε as a fraction of g, not x, since normally you would want to say that the result has some precision ("six digits", for example) which is necessarily​ relative to the result. But it doesn't make much difference aside from interpreting the meaning of the ε parameter.
It is certainly the case that choosing some absolute error threshold makes no sense unless you know that the possible arguments are within a very restricted set of values.

Related

Calculate the displacement coordinates of a semi-articulated truck

As shown in the image below, I'm creating a program that will make a 2D animation of a truck that is made up of two articulated parts.
The truck pulls the trailer.
The trailer moves according to the docking axis on the truck.
Then, when the truck turns, the trailer should gradually align itself with the new angle of the truck, as it does in real life.
I would like to know if there is any formula or algorithm that does this calculation in an easy way.
I've already seen inverse kinematics equations, but I think for just 2 parts it would not be so complex.
Can anybody help me?
Let A be the midpoint under the front axle, B be the midpoint under the middle axle, and C be the midpoint under the rear axle. For simplicity assume that the hitch is at point B. These are all functions of time t, for example A(t) = (a_x(t), a_y(t).
The trick is this. B is moving directly towards A with the component of A's velocity in that direction. Or in symbols, dB/dt = (dA/dt).(A-B)/||A-B|| And similarly, dC/dt = (dB/dt).(B-C)/||B-C|| where . is the dot product.
This turns into a non-linear first-order system in 6 variables. This can be solved with normal techniques, such as https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods.
UPDATE: Added code
Here is a Python implementation. You can replace it with https://rosettacode.org/wiki/Runge-Kutta_method for your favorite language and your favorite linear algebra library. Or even hand-roll that.
For my example I started with A at (1, 1), B at (2, 1) and C at (2, 2). Then pulled A to the origin in steps of size 0.01. That can be altered to anything that you want.
#! /usr/bin/env python
import numpy
# Runga Kutta method.
def RK4(f):
return lambda t, y, dt: (
lambda dy1: (
lambda dy2: (
lambda dy3: (
lambda dy4: (dy1 + 2*dy2 + 2*dy3 + dy4)/6
)( dt * f( t + dt , y + dy3 ) )
)( dt * f( t + dt/2, y + dy2/2 ) )
)( dt * f( t + dt/2, y + dy1/2 ) )
)( dt * f( t , y ) )
# da is a function giving velocity of a at a time t.
# The other three are the positions of the three points.
def calculate_dy (da, A0, B0, C0):
l_ab = float(numpy.linalg.norm(A0 - B0))
l_bc = float(numpy.linalg.norm(B0 - C0))
# t is time, y = [A, B, C]
def update (t, y):
(A, B, C) = y
dA = da(t)
ab_unit = (A - B) / float(numpy.linalg.norm(A-B))
# The first term is the force. The second is a correction to
# cause roundoff errors in length to be selfcorrecting.
dB = (dA.dot(ab_unit) + float(numpy.linalg.norm(A-B))/l_ab - l_ab) * ab_unit
bc_unit = (B - C) / float(numpy.linalg.norm(B-C))
# The first term is the force. The second is a correction to
# cause roundoff errors in length to be selfcorrecting.
dC = (dB.dot(bc_unit) + float(numpy.linalg.norm(B-C))/l_bc - l_bc) * bc_unit
return numpy.array([dA, dB, dC])
return RK4(update)
A0 = numpy.array([1.0, 1.0])
B0 = numpy.array([2.0, 1.0])
C0 = numpy.array([2.0, 2.0])
dy = calculate_dy(lambda t: numpy.array([-1.0, -1.0]), A0, B0, C0)
t, y, dt = 0., numpy.array([A0, B0, C0]), .02
while t <= 1.01:
print( (t, y) )
t, y = t + dt, y + dy( t, y, dt )
By the answers I saw, I realized that the solution is not really simple and will have to be solved by an Inverse Kinematics algorithm.
This site is an example and it is a just a start, although it still does not solve everything, since the point C is fixed and in the case of the truck it should move.
Based on this Analytic Two-Bone IK in 2D article, I made a fully functional model in Geogebra, where the nucleus consists of two simple mathematical equations.

Maxima: how to reform a equation in a defined format

In Maxima, I want to change the following equation:
ax+b-c-d=0
into the following format
(ax+b)/(c+d)=1
Note:
something like ax+b-c-d+1=1 is not what I want.
Basically I want to have positive elements in one side and negative elements in another side, then divide the positive elements by the negative elements.
Here is a quick attempt. It handles some equations of the form you described, but it's probably easy to find some which it can't handle. Maybe it works well enough, or at least provides some inspiration.
ptermp (e) := symbolp(e) or (numberp(e) and e > 0)
or ((op(e) = "+" or op(e) = "*") and every (ptermp, args(e)));
matchdeclare (pterm, ptermp);
matchdeclare (otherterm, all);
defrule (r1, pterm + otherterm = 0, ratsimp (pterm/(-otherterm)) = 1);
NOTE: the catch-all otherterm must be precede pterm alphabetically! This is a useful, but obscure, consequence of the simplification of "+" expressions and the pattern-matching process ... sorry for the obscurity.
Examples:
apply1 (a*x - b - c + d = 0, r1);
a x + d
------- = 1
c + b
apply1 (a*x - (b + g) - 2*c + d*e*f = 0, r1);
a x + d e f
----------- = 1
g + 2 c + b

Ordered set and natural bijection (combinatorial species)

Let A some set (eg. 1000, 1001, 1002, ..., 1999).
Let lessThan some order relation function (eg. (a lessThan b) <-> (a > b)).
Let index a function (with inverse index') mapping a A element to naturals.
Example:
index a = 2000 - a
index' n = 2000 - n
Exists some way to construct index (and index') function for all (or some kinds of) (A, lessThan) pairs in P (polynomial time)?
Best regards and thank's in advance!
EDITED: A could be a set by definition (eg. all combinations with repetition of another big subset), then, we can't suppose A is completely traversable (in P).
EDITED: another non trivial example, let An a set (with elements like (x, y, p)) whose elements are ordered clockwise into a n X n square, like this
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
then, we can map each triplet in An to Bn = [1..n^2] with O(1) (a polynomial).
Given one An element we can index to Bn with O(1).
Given one Bn element we can index' to An with O(1).
// Square perimeter; square x = 1, 2, 3, ...
Func<int, int, int> perimeter = ( x, n ) => 4 * ( n - 2 * x + 1 );
// Given main diagonal coordinates (1, 1), (2, 2), ... return cell number
Func<int, int, int> diagonalPos = ( x, n ) => -4 * x * x + ( 4 * n + 8 ) * x - 4 * n - 3;
// Given a number, return their square
Func<int, int, int> inSquare = ( z, n ) => (int) Math.Floor(n * 0.5 - 0.5 * Math.Sqrt(n * n - z + 1.0) + 1.0);
Func<int, int, Point> coords = ( z, n ) => {
var s = inSquare(z, n);
var l = perimeter(s, n) / 4; // length sub-square edge -1
var l2 = l + l;
var l3 = l2 + l;
var d = diagonalPos(s, n);
if( z <= d + l )
return new Point(s + z - d, s);
if( z <= d + l2 )
return new Point(s + l, s + z - d - l);
if( z <= d + l3 )
return new Point(s + d + l3 - z, s + l);
return new Point(s, s + d + l2 + l2 - z);
};
(I have read about "Combinatorial species", "Ordered construction of combinatorial objects", "species" haskell package and others)
I may be misunderstanding what you want, but in case I'm not:
If lessThan defines a total order on the set, you can create the index and index' functions by
converting the set to a list (or an array/vector)
sorting that according to lessThan
construct index' as Data.Map.fromDistinctAscList $ zip [1 .. ] sortedList
construct index as Data.Map.fromDistinctAscList $ zip (map NTC sortedList) [1 .. ]
where NTC is a newtype constructor wrapping the type of elements of the set in a newtype whose Ord instance is given by lessThan.
newtype Wrapped = NTC typeOfElements
instance Eq Wrapped where
(NTC x) /= (NTC y) = x `lessThan` y || y `lessThan` x
-- that can usually be done more efficiently
instance Ord Wrapped where
(NTC x) <= (NTC y) = not $ y `lessThan` x
EDITED: A could be a set by definition (eg. all combinations with repetition of another big subset), then, we can't suppose A is completely traversable (in P).
In that case, unless I'm missing something fundamental, it's impossible in principle, because the index' function would provide a complete traversal of the set.
So you can create the index and index' functions in polynomial time if and only if the set is traversable in polynomial time.

Matlab wrong results with array calculations

I'm trying to reproduce the results from a paper for which I give a link to avoid writing down all the math needed:
On Modeling and Simulation of Game Theory-based Defense Mechanisms against DoS and DDoS Attacks
More specifically what I'm having a problem with is the Figure 3 plot. The plot gives in the z axis the results of equation 3 given the two variables m and M. The other equations that will be needed are 5,6,7 and there are also two small ones in the paragraph before equation 6. Also in order to see what Xi is check the 4.2 part. All the variable values needed are given before the plot.
Now to get to the point, I'm trying to create the exact same plot in matlab but I've failed and I need help because my matlab skills are not so good.
I have a script file in which I have the following:
w1 = 1000;
w2 = 1000;
w3 = 10;
B = 2000;
n = 20;
r_l = 60;
s_l = 20;
g = 10;
a_f = 5000;
b = 20;
vx = 0 : 1 : 500;
vy = 0 : 1 : 90;
[x,y] = meshgrid(vx,vy);
z = payoff(w1, w2, w3, y, r_l, n, g, B, b, x, s_l, a_f);
h = surfc(x,y,z);
set(h, 'edgecolor','none')
xlabel('Firewall Midpoint (M)')
ylabel('Number of zombies')
zlabel('Attackers payoff')
view(-41,11);
Payoff is a function that is as follows:
function out = payoff(w1, w2, w3, m, r_l, n, g, B, b, M, s_l, a_f)
r_a = a_f./ m;
r_a_dash = r_a.*(1-Fx(r_a, b, M, B));
r_l_dash = r_l.*(1-Fx(r_l, b, M, B));
v_b = ( m .* r_a_dash ) ./ ( n .* r_l_dash + m .* r_a_dash );
v_n = normcdf(( g .* ( n .* r_l_dash + m .* r_a_dash ) ./ B ), r_l, s_l);
out = w1 * v_b + w2 * v_n - w3 * m;
Fx again is a function that does the following:
function out = Fx(x,b,M,B)
out=1./(1+exp(-b.*(x-M)./B));
I don't know where exactly is the mistake but the plot I get is the following which is not the same as the one in the paper.
The figure in the paper has a U shaped curve along the Firewall Midpointaxis whereas mine is monotonically increasing.
Can anyone spot any mistake(s) that I have? Thanks in advance.
The big thing I noticed was in your code you used:
v_n = normcdf(( g .* ( n .* r_l_dash + m .* r_a_dash ) ./ B ), r_l, s_l);
When you should have used (I think):
v_n = normcdf(( g .* ( n .* r_l_dash + m .* r_a_dash ) ./ B ), r_l_dash, s_l);
In the paper, they state:
Recall that rl represents the expected rate of a legitimate flow. Let the average rate of legitimate flows passing through the firewall be rl′.
In the normcdf function, the second argument should be the average, mu. This gives me a U-shaped curve along the Firewall Midpoint, however I can see it's not exact to the picture and I believe it's due to the value of b, as someone had already stated was not given.
Hope this helps. There may still be a calculation error as I've played around with various values of b and still can't match the image in the paper.

Reduction from Atm to A (of my choice) , and from A to Atm

Reduction of many one , is not symmetric . I'm trying to prove it but it doesn't work
so well .
Given two languages A and B ,where A is defined as
A={w| |w| is even} , i.e. `w` has an even length
and B=A_TM , where A_TM is undecidable but Turing-recognizable!
Given the following Reduction:
f(w) = { (P(x):{accept;}),epsilon , if |w| is even
f(w) = { (P(x):{reject;}),epsilon , else
(Please forgive me for not using Latex , I have no experience with it)
As I can see, a reduction from A <= B (from A to A_TM) is possible , and works great.
However , I don't understand why B <= A , is not possible .
Can you please clarify and explain ?
Thanks
Ron
Assume for a moment that B <= A. Then there is a function f:Sigma*->Sigma* such that:
f(w) = x in A if w is in B
= x not in A if w is not in B
Therefore, we can describe the following algorithm [turing machine] M on input w:
1. w' <- f(w)
2. if |w'| is even return true
3. return false
It is easy to prove that M accepts w if and only if w is in B [left as an exercise to the reader], thus L(M) = B.
Also, M stops for any input w [from its construction]. Thus - L(M) is decideable.
But we got that L(M) = B is decideable - and that is a contradiction, because B = A_TM is undecideable!

Resources