Formula to obtain amount to add to Starting Value so the added amount will = 5% of New Total - tsql

Is there a formula that will work in T-SQL that can obtain the following?
Solve for x where adding x to starting value, will equal 105% of starting value.
Example
Starting value of 380.
Add x to 380 so that x is 5% of total (380 + x)
In this case, x is an even 20.
This is not 5% of the Starting value, which, would be simple. I'm looking for x to equal 5% of the new value after it's been added to the starting value.
Thank you!

I'm looking for x to equal 5% of the new value after it's been added to the starting value.
Let's do some 9th grade algebra :) I'll even show my work.
If S is the starting value, we have this equation:
x = 0.05 * (S + x)
Now solve for x:
x = 0.05S + 0.05x // distribute the constant
0.95x = 0.05S // subtract the smaller x term from both sides
x = (0.05 / 0.95) * S // divide the 0.95 from both sides
x = S / 19 // multiply the right side by 1 (20/20) to simplify
So we see you can divide the starting value by 19 to get the desired x value.
And an alternative way to solve the equation, because I think this kind of thing is fun:
x = (1/20) * (S + x) // convert the decimal to a fraction
x = (S + x) / 20 // reduce/simplify the fraction multiplication
20x = S + x // multiply both sides by 20, to remove division
19x = S // subtract the smaller x term from both sides
// (hey, we solved for S along the way)
x = S / 19 // Divide both sides by 19
It's always nice when two approaches give the same solution :). This was more steps, but the steps were simpler.

Related

how to prove that the hash function h(x) = x² mod 4 yields only to 0 and 1

How can I prove that the hash function h(x) = x² mod 4 yields only to {0, 1}, with x as an element of the natural numbers?
Let's first cover the even numbers, 2n (where n is a natural number):
(2n)2
= (2n)(2n)
= (2)(n)(2)(n)
= (2)(2)(n)(n)
= 4n2
= 4(n2)
That's an exact multiple of four so the remainder when dividing by four will always be zero.
Now let's cover the odd numbers, 2n + 1:
(2n + 1)2
= (2n + 1)(2n + 1)
= (2n)(2n) + (2n)(1) + (1)(2n) + (1)(1)
= 4n2 + 2n + 2n + 1
= 4n2 + 4n + 1
= 4(n2 + n) + 1
That's exactly one more than a multiple of four hence the remainder when dividing by four will always be one.
Now, let's look at any natural numbers that are neither even nor odd.
Wait a minute, there aren't any. I guess that means we're done :-)
And, before anyone points out that some languages may give a negative remainder when the arguments are negative, that doesn't actually apply here since the square of a natural number can never be negative.

Matlab : How to represent a real number as binary

Problem : How do I use a continuous map - The Link1: Bernoulli Shift Map to model binary sequence?
Concept :
The Dyadic map also called as the Bernoulli Shift map is expressed as x(k+1) = 2x(k) mod 1. In Link2: Symbolic Dynamics, explains that the Bernoulli Map is a continuous map and is used as the Shift Map. This is explained further below.
A numeric trajectory can be symbolized by partitioning into appropriate regions and assigning it with a symbol. A symbolic orbit is obtained by writing down the sequence of symbols corresponding to the successive partition elements visited by the point in its orbit. One can learn much about the dynamics of the system by studying its symbolic orbits. This link also says that the Bernoulli Shift Map is used to represent symbolic dynamics.
Question :
How is the Bernoulli Shift Map used to generate the binary sequence? I tried like this, but this is not what the document in Link2 explains. So, I took the numeric output of the Map and converted to symbols by thresholding in the following way:
x = rand();
y = mod(2* x,1) % generate the next value after one iteration
y =
0.3295
if y >= 0.5 then s = 1
else s = 0
where 0.5 is the threshold value, called the critical value of the Bernoulli Map.
I need to represent the real number as fractions as explained here on Page 2 of Link2.
Can somebody please show how I can apply the Bernoulli Shift Map to generate symbolized trajectory (also called time series) ?
Please correct me if my understanding is wrong.
How do I convert a real valued numeric time series into symbolized i.e., how do I use the Bernoulli Map to model binary orbit /time series?
You can certainly compute this in real number space, but you risk hitting precision problems (depending on starting point). If you're interested in studying orbits, you may prefer to work in a rational fraction representation. There are more efficient ways to do this, but the following code illustrates one way to compute a series derived from that map. You'll see the period-n definition on page 2 of your Link 2. You should be able to see from this code how you could easily work in real number space as an alternative (in that case, the matlab function rat will recover a rational approximation from your real number).
[EDIT] Now with binary sequence made explicit!
% start at some point on period-n orbit
period = 6;
num = 3;
den = 2^period-1;
% compute for this many steps of the sequence
num_steps = 20;
% for each step
for n = 1:num_steps
% * 2
num = num * 2;
% mod 1
if num >= den
num = num - den;
end
% simplify rational fraction
g = gcd(num, den);
if g > 1
num = num / g;
den = den / g;
end
% recover 8-bit binary representation
bits = 8;
q = 2^bits;
x = num / den * q;
b = dec2bin(x, bits);
% display
fprintf('%4i / %4i == 0.%s\n', num, den, b);
end
Ach... for completeness, here's the real-valued version. Pure mathematicians should look away now.
% start at some point on period-n orbit
period = 6;
num = 3;
den = 2^period-1;
% use floating point approximation
x = num / den;
% compute for this many steps of the sequence
num_steps = 20;
% for each step
for n = 1:num_steps
% apply map
x = mod(x*2, 1);
% display
[num, den] = rat(x);
fprintf('%i / %i\n', num, den);
end
And, for extra credit, why is this implementation fast but daft? (HINT: try setting num_steps to 50)...
% matlab vectorised version
period = 6;
num = 3;
den = 2^period-1;
x = zeros(1, num_steps);
x(1) = num / den;
y = filter(1, [1 -2], x);
[a, b] = rat(mod(y, 1));
disp([a' b']);
OK, this is supposed to be an answer, not a question, so let's answer my own questions...
It's fast because it uses Matlab's built-in (and highly optimised) filter function to handle the iteration (that is, in practice, the iteration is done in C rather than in M-script). It's always worth remembering filter in Matlab, I'm constantly surprised by how it can be turned to good use for applications that don't look like filtering problems. filter cannot do conditional processing, however, and does not support modulo arithmetic, so how do we get away with it? Simply because this map has the property that whole periods at the input map to whole periods at the output (because the map operation is multiply by an integer).
It's daft because it very quickly hits the aforementioned precision problems. Set num_steps to 50 and watch it start to get wrong answers. What's happening is the number inside the filter operation is getting to be so large (order 10^14) that the bit we actually care about (the fractional part) is no longer representable in the same double-precision variable.
This last bit is something of a diversion, which has more to do with computation than maths - stick to the first implementation if your interest lies in symbol sequences.
If you only want to deal with rational type of output, you'll first have to convert the starting term of your series into a rational number if it is not. You can do that with:
[N,D] = rat(x0) ;
Once you have a numerator N and a denominator D, it is very easy to calculate the series x(k+1)=mod(2*x(k), 1) , and you don't even need a loop.
for the part 2*x(k), it means all the Numerator(k) will be multiplied by successive power of 2, which can be done by matrix multiplication (or bsxfun for the lover of the function):
so 2*x(k) => in Matlab N.*(2.^(0:n-1)) (N is a scalar, the numerator of x0, n is the number of terms you want to calculate).
The Mod1 operation is also easy to translate to rational number: mod(x,1)=mod(Nx,Dx)/Dx (Nx and Dx being the numerator and denominator of x.
If you do not need to simplify the denominator, you could get all the numerators of the series in one single line:
xn = mod( N.*(2.^(0:n-1).'),D) ;
but for visual comfort, it is sometimes better to simplify, so consider the following function:
function y = dyadic_rat(x0,n)
[N,D] = rat(x0) ; %// get Numerator and Denominator of first element
xn = mod( N.*(2.^(0:n-1).'),D) ; %'// calculate all Numerators
G = gcd( xn , D ) ; %// list all "Greatest common divisor"
y = [xn./G D./G].' ; %'// output simplified Numerators and Denominators
If I start with the example given in your wiki link (x0=11/24), I get:
>> y = dyadic_rat(11/24,8)
y =
11 11 5 2 1 2 1 2
24 12 6 3 3 3 3 3
If I start with the example given by Rattus Ex Machina (x0=3/(2^6-1)), I also get the same result:
>> y = dyadic_rat(3/63,8)
y =
1 2 4 8 16 11 1 2
21 21 21 21 21 21 21 21

Create an increasing integer alternating sequence in MATLAB / Octave

I'm trying to find a way to create a number pattern like the one below
0,1,-2,3,-4,5....
Please note: it needs to go to 200000, but I will be splitting them up into groups of 2000.
I found a formula that looks like it would work on http://oeis.org/A181983, but when I create the formula in MATLAB / Octave, the numbers don't match up:
f_num= #(x) x / (1 + x)^2;
numval = f_num(1)
numval = 0.25000
Is there another way I should be doing this?
Method #1 - Using (-1)^x
Just use a linear increment operator to go from 0 to 200000 and multiply the sequence by (-1)^(x+1) to allow the sign of the sequence to alternate:
x = 0:200000;
y = ((-1).^(x+1)) .* x;
The addition of the +1 is important so that the even positions get a positive sign while the odd positions get a negative sign.
Method #2 - Using indexing
Alternatively, you can declare the same array from 0 to 200000, index into every even position and negate the sign:
x = 0:200000;
x(2:2:end) = -x(2:2:end);
Method #3 - Using trigonometry and integers
One more to throw into the mix. You know that for cos(x*pi), the output is -1 when x is odd and the output is 1 when x is even. We need to flip this for your case and ultimately use this alternating sequence to multiply with the same array going from 0 to 200000, and therefore:
x = 0:200000;
y = (-cos(x*pi)).*x;
Aside
Interestingly enough, (-1)^x is also equal to exp(i*pi*x) for all values of x that are integer. We can verify this by using Euler's formula where: exp(i*pi*x) = cos(pi*x) + i*sin(pi*x). Since i*sin(pi*x) = 0 for all x belonging to an integer, we really get exp(i*pi*x) = cos(pi*x). Substituting even numbers of x will give us 1 while odd numbers of x will give us -1, and hence exp(i*pi*x) = cos(pi*x) = (-1)^x for all x belonging to integers.
Also, (-1)^(x+1) = -(-1)^x = -cos(x*pi) for all x belonging to integers and so the first method is really equal to the third method anyway!
try
f_num= #(x) x * (-1)^(x+1);

What is the Haskell / hmatrix equivalent of the MATLAB pos function?

I'm translating some MATLAB code to Haskell using the hmatrix library. It's going well, but
I'm stumbling on the pos function, because I don't know what it does or what it's Haskell equivalent will be.
The MATLAB code looks like this:
[U,S,V] = svd(Y,0);
diagS = diag(S);
...
A = U * diag(pos(diagS-tau)) * V';
E = sign(Y) .* pos( abs(Y) - lambda*tau );
M = D - A - E;
My Haskell translation so far:
(u,s,v) = svd y
diagS = diag s
a = u `multiply` (diagS - tau) `multiply` v
This actually type checks ok, but of course, I'm missing the "pos" call, and it throws the error:
inconsistent dimensions in matrix product (3,3) x (4,4)
So I'm guessing pos does something with matrix size? Googling "matlab pos function" didn't turn up anything useful, so any pointers are very much appreciated! (Obviously I don't know much MATLAB)
Incidentally this is for the TILT algorithm to recover low rank textures from a noisy, warped image. I'm very excited about it, even if the math is way beyond me!
Looks like the pos function is defined in a different MATLAB file:
function P = pos(A)
P = A .* double( A > 0 );
I can't quite decipher what this is doing. Assuming that boolean values cast to doubles where "True" == 1.0 and "False" == 0.0
In that case it turns negative values to zero and leaves positive numbers unchanged?
It looks as though pos finds the positive part of a matrix. You could implement this directly with mapMatrix
pos :: (Storable a, Num a) => Matrix a -> Matrix a
pos = mapMatrix go where
go x | x > 0 = x
| otherwise = 0
Though Matlab makes no distinction between Matrix and Vector unlike Haskell.
But it's worth analyzing that Matlab fragment more. Per http://www.mathworks.com/help/matlab/ref/svd.html the first line computes the "economy-sized" Singular Value Decomposition of Y, i.e. three matrices such that
U * S * V = Y
where, assuming Y is m x n then U is m x n, S is n x n and diagonal, and V is n x n. Further, both U and V should be orthonormal. In linear algebraic terms this separates the linear transformation Y into two "rotation" components and the central eigenvalue scaling component.
Since S is diagonal, we extract that diagonal as a vector using diag(S) and then subtract a term tau which must also be a vector. This might produce a diagonal containing negative values which cannot be properly interpreted as eigenvalues, so pos is there to trim out the negative eigenvalues, setting them to 0. We then use diag to convert the resulting vector back into a diagonal matrix and multiply the pieces back together to get A, a modified form of Y.
Note that we can skip some steps in Haskell as svd (and its "economy-sized" partner thinSVD) return vectors of eigenvalues instead of mostly 0'd diagonal matrices.
(u, s, v) = thinSVD y
-- note the trans here, that was the ' in Matlab
a = u `multiply` diag (fmap (max 0) s) `multiply` trans v
Above fmap maps max 0 over the Vector of eigenvalues s and then diag (from Numeric.Container) reinflates the Vector into a Matrix prior to the multiplys. With a little thought it's easy to see that max 0 is just pos applied to a single element.
(A>0) returns the positions of elements of A which are larger than zero,
so forexample, if you have
A = [ -1 2 -3 4
5 6 -7 -8 ]
then B = (A > 0) returns
B = [ 0 1 0 1
1 1 0 0]
Note that we have ones corresponding to an elemnt of A which is larger than zero, and 0 otherwise.
Now if you multiply this elementwise with A using the .* notation, then you are multipling each element of A that is larger than zero with 1, and with zero otherwise. That is, A .* B means
[ -1*0 2*1 -3*0 4*1
5*1 6*1 -7*0 -8*0 ]
giving finally,
[ 0 2 0 4
5 6 0 0 ]
So you need to write your own function that will return positive values intact, and negative values set to zero.
And also, u and v does not match in dimension, for a generall SVD decomposition, so you actually would need to REDIAGONALIZE pos(diagS - Tau), so that u* diagnonalized_(diagS -tau) agrres to v

Media-of-3 partitioning in QuickSort

I was trying to understand quicksort with median-of-3 partitioning. After finding the median of the first, middle and last element in an array, a common practice is to swap median with the second last element in array(n-1th index). Is there a specific reason we do that?
The reason is that the algorithm does not only find the median, it also sorts the low, middle and high elements. After the three permutations you know that a[middle]<=a[high]. So you need only to partition the elements before high, because a[high] is greater or equal to pivot.
Let's look at an example: low=0, middle=4 and high=8. Your array is like this:
lowerOrEqualToPivot X X X pivot X X X greaterOrEqualToPivot
If you swap middle with high, you need to partition the 8 elements between brackets :
[ lowerOrEqualToPivot X X X greaterOrEqualToPivot X X X ] pivot
If you swap middle with high-1, you need to split only 7 elements:
[ lowerOrEqualToPivot X X X X X X ] pivot greaterOrEqualToPivot
By the way there is a bug in the first line:
int middle = ( low + high ) / 2; //Wrong
int middle = ( low + high ) >>> 1; //Correct
The reason is that if (low + high) is greater than Integer.MAX_VALUE you will have an overflow and middle will be a negative number. The second line will always give you a positive result.