Exponential moving average in J - moving-average

I currently am going through some examples of J, and am trying to do an exponential moving average.
For the simple moving average I have done as follows:
sma =: +/%[
With the following given:
5 sma 1 2 3 4 5
1.2 1.4 1.6 1.8 2
After some more digging I found an example of the exponential moving average in q.
.q.ema:{first[y]("f"$1-x)\x*y}
I have tried porting this to J with the following code:
ema =: ({. y (1 - x)/x*y)
However this results in the following error:
domain error
| ema=:({.y(1-x) /x*y)
This is with x = 20, and y an array of 20 random numbers.

A couple of things that I notice that might help you out.
1) When you declare a verb explicitly you need to use the : Explicit conjunction and in this case since you have a dyadic verb the correct form would be 4 : 'x contents of verb y' Your first definition of sma =: +/%[ is tacit, since no x or y variables are shown.
ema =: 4 : '({. y (1 - x)/x*y)'
2) I don't know q, but in J it looks as if you are trying to Insert / a noun 1 - x into a list of integers x * y. I am guessing that you really want to Divides %. You can use a gerunds as arguments to Insert but they are special nouns representing verbs and 1 - x does not represent a verb.
ema =: 4 : '({. y (1 - x)%x*y)'
3) The next issue is that you would have created a list of numbers with (1 - x) % x * y, but at that point y is a number adjacent to a list of numbers with no verb between which will be an error. Perhaps you meant to use y * (1 - x)%x*y ?
At this point I am not sure what you want exponential moving average to do and hope the clues I have provided will give you the boost that you need.

Related

Unnormalizing in Knuth's Algorithm D

I'm trying to implement Algorithm D from Knuth's "The Art of Computer Programming, Vol 2" in Rust although I'm having trouble understating how to implement the very last step of unnormalizing. My natural numbers are a class where each number is a vector of u64, in base u64::MAX. Addition, subtraction, and multiplication have been implemented.
Knuth's Algorithm D is a euclidean division algorithm which takes two natural numbers x and y and returns (q,r) where q = x / y (integer division) and r = x % y, the remainder. The algorithm depends on an approximation method which only works if the first digit of y is greater than b/2, where b is the base you're representing the numbers in. Since not all numbers are of this form, it uses a "normalizing trick", for example (if we were in base 10) instead of doing 200 / 23, we calculate a normalizer d and do (200 * d) / (23 * d) so that 23 * d has a first digit greater than b/2.
So when we use the approximation method, we end up with the desired q but the remainder is multiplied by a factor of d. So the last step is to divide r by d so that we can get the q and r we want. My problem is, I'm a bit confused at how we're suppose to do this last step as it requires division and the method it's part of is trying to implement division.
(Maybe helpful?):
The way that d is calculated is just by taking the integer floor of b-1 divided by the first digit of y. However, Knuth suggests that it's possible to make d a power of 2, as long as d * the first digit of y is greater than b / 2. I think he makes this suggestion so that instead of dividing, we can just do a binary shift for this last step. Although I don't think I can do that given that my numbers are represented as vectors of u64 values, instead of binary.
Any suggestions?

Prolog: how to optimize this code(Solving 123456789=100 puzzle)

So there was a puzzle:
This equation is incomplete: 1 2 3 4 5 6 7 8 9 = 100. One way to make
it accurate is by adding seven plus and minus signs, like so: 1 + 2 +
3 – 4 + 5 + 6 + 78 + 9 = 100.
How can you do it using only 3 plus or minus signs?
I'm quite new to Prolog, solved the puzzle, but i wonder how to optimize it
makeInt(S,F,FinInt):-
getInt(S,F,0,FinInt).
getInt(Start, Finish, Acc, FinInt):-
0 =< Finish - Start,
NewAcc is Acc*10 + Start,
NewStart is Start +1,
getInt(NewStart, Finish, NewAcc, FinInt).
getInt(Start, Finish, A, A):-
0 > Finish - Start.
itCounts(X,Y,Z,Q):-
member(XLastDigit,[1,2,3,4,5,6]),
FromY is XLastDigit+1,
numlist(FromY, 7, ListYLastDigit),
member(YLastDigit, ListYLastDigit),
FromZ is YLastDigit+1,
numlist(FromZ, 8, ListZLastDigit),
member(ZLastDigit,ListZLastDigit),
FromQ is ZLastDigit+1,
member(YSign,[-1,1]),
member(ZSign,[-1,1]),
member(QSign,[-1,1]),
0 is XLastDigit + YSign*YLastDigit + ZSign*ZLastDigit + QSign*9,
makeInt(1, XLastDigit, FirstNumber),
makeInt(FromY, YLastDigit, SecondNumber),
makeInt(FromZ, ZLastDigit, ThirdNumber),
makeInt(FromQ, 9, FourthNumber),
X is FirstNumber,
Y is YSign*SecondNumber,
Z is ZSign*ThirdNumber,
Q is QSign*FourthNumber,
100 =:= X + Y + Z + Q.
Not sure this stands for an optimization. The code is just shorter:
sum_123456789_eq_100_with_3_sum_or_sub(L) :-
append([G1,G2,G3,G4], [0'1,0'2,0'3,0'4,0'5,0'6,0'7,0'8,0'9]),
maplist([X]>>(length(X,N), N>0), [G1,G2,G3,G4]),
maplist([G,F]>>(member(Op, [0'+,0'-]),F=[Op|G]), [G2,G3,G4], [F2,F3,F4]),
append([G1,F2,F3,F4], L),
read_term_from_codes(L, T, []),
100 is T.
It took me a while, but I got what your code is doing. It's something like this:
itCounts(X,Y,Z,Q) :- % generate X, Y, Z, and Q s.t. X+Y+Z+Q=100, etc.
generate X as a list of digits
do the same for Y, Z, and Q
pick the signs for Y, Z, and Q
convert all those lists of digits into numbers
verify that, with the signs, they add to 100.
The inefficiency here is that the testing is all done at the last minute. You can improve the efficiency if you can throw out some possible solutions as soon as you pick one of your numbers, that is, testing earlier.
itCounts(X,Y,Z,Q) :- % generate X, Y, Z, and Q s.t. X+Y+Z+Q=100, etc.
generate X as a list of digits, and convert it to a number
if it's so big or small the rest can't possibly bring the sum back to 100, fail
generate Y as a list of digits, convert to number, and pick it sign
if it's so big or so small the rest can't possibly bring the sum to 100, fail
do the same for Z
do the same for Q
Your function is running pretty fast already, even if I search all possible solutions. It only picks 6 X's; 42 Y's; 224 Z's; and 15 Q's. I don't think optimizing will be worth your while.
But if you really wanted to: I tested this by putting a testing function immediately after selecting an X. It reduced the 6 X's to 3 (all before finding the solution); 42 Y's to 30; 224 Z's to 184; and 15 Q's to 11. I believe we could reduce it further by testing immediately after a Y is picked, to see whether X YSign Y is already so large or small there can be no solution.
In PROLOG programs that are more computationally intensive, putting parts of the 'test' earlier in 'generate and test' algorithms can help a lot.

When does floating-point rounding-errors occur? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 7 years ago.
As I was debugging my VBA code, I came across this weird phenomenon:
This loop
Dim x,y as Double
x = 0.7
y = 0.1
For x = x - y To x + y Step y
Next x
runs only twice!
I tried many variations of this code to nail down the problem, and here is what I came up with:
Replacing the loop boundaries with simple numbers (0.6 to 0.8) - helped.
Replacing variables with numbers (all the combinations) - didn't help.
Replacing the for-loop with do while/until loops - helped.
Replacing the values of x and y (y=0.01, 0.3, 0.4, 0.5, 0.7, 0.8, 0.9 - helped. 0.2, 0.6 -didn't help. x=1, 2 ,3 helped. x=4, 5, 6, 7, 8, 9 - didn't help.
Converting the Double to Decimal with CDec() - helped.
Using the Currency data type instead of Double - helped.
So what we have here is a floating-point rounding-error that happens on mysterious conditions.
What I'm trying to find out is what are those conditions, so we can avoid them.
Who will unveil this mystery?
(Pardon my English, it's not my mother tongue).
GD Falcon,
Generally in solving a For...Next loop it would not be advisable to use 'double' or 'decimal' or 'currency' variables as they provide a level of uncertainty in their accuracy, it's this level of inaccuracy that is wrecking havoc on your code as the actual stop parameter (when x-y, plus (n x y) = x+y) is, in terms of absolutes, an insolvable equation unless you limit the number of decimals it uses.
It is generally considered better practice to use integers (or long) variables in a For...Next loop as their outcome is more certain.
See also below post:
How to make For loop work with non integers
If you want it to run succesfully and iterate 3 times (as I expect you want)
Try like below:
Dim x, y As Double
x = 0.7
y = 0.1
For x = Round(x - y, 1) To Round(x + y, 1) Step Round(y, 1)
Debug.Print x
Next x
Again, it is better not to use Doubles in this particular way to begin with but if you must you would have to limit the number of decimals they calculate with or set a more vague end point (i.e. x > y, rather than x = y)
The coding you use implies that you wish to test some value x against a tolerance level of y.
Assuming this is correct it would imply testing 3 times where;
test_1: x = x - y
test_2: x = x
test_3: x = x + y
The below code would do the same but it would have a better defined scope.
Dim i As Integer
Dim x, y, w As Double
x = 0.7
y = 0.1
For i = -1 To 1 Step 1
w = x + (i * y)
Debug.Print w
Next i
Good luck !

What does a percentage sign (%) do mathematically in Objective C?

I am super confused what the percentage sign does in Objective C. Can someone explain to me in language that an average idiot like myself can understand?! Thanks.
% is the modulo operator, so for example 10 % 3 would result in 1.
If you have some numbers a and b, a % b gives you just the remainder of a divided by b.
So in the example 10 % 3, 10 divided by 3 is 3 with remainder 1, so the answer is 1.
If there is no remainder to a divided by b, the answer is zero, so for example, 4 % 2 = 0.
Here's a relevant SO question about modular arithmetic.
Same as what it does in C, it's "modulo" (also known as integer remainder).
% is the modulo operator. It returns the remainder of <number> / <number>. For example:
5 % 2
means 5 / 2, which equals 2 with a remainder of 1, so, 1 is the value that is returned. Here's some more examples:
3 % 3 == 0 //remainder of 3/3 is 0
6 % 3 == 0 //remainder of 6/3 is 0
5 % 3 == 2 //remainder of 5/3 is 2
15 % 4 == 3 //remainder of 15/4 is 3
99 % 30 == 9 //remainder of 99/30 is 9
The definition of modulo is:
mod·u·lo
(in number theory) with respect to or using a modulus of a specified number. Two numbers are congruent modulo a given number if they give the same remainder when divided by that number.
In Mathematics, The Percentage Sign %, Called Modulo (Or Sometimes The Remainder Operator) Is A Operator Which Will Find The Remainder Of Two Numbers x And y. Mathematically Speaking, If x/y = {(z, r) : y * z + r = x}, Where All x, y, and z Are All Integers, Then
x % y = {r: ∃z: x/y = (z, r)}. So, For Example, 10 % 3 = 1.
Some Theorems And Properties About Modulo
If x < y, Then x % y = x
x % 1 = 0
x % x = 0
If n < x, Then (x + n) % x = n
x Is Even If And Only If x % 2 = 0
x Is Odd If And Only If x % 2 = 1
And Much More!
Now, One Might Ask: How Do We Find x % y? Well, Here's A Fairly Simple Way:
Do Long Division. I Could Explain How To Do It, But Instead, Here's A Link To A Page Which Explains Long Division: https://www.mathsisfun.com/numbers/long-division-index.html
Stop At Fractions. Once We Reach The Part Where We Would Normally Write The Answer As A Fraction, We Should Stop. So, For Example, 101/2 Would Be 50.5, But, As We Said, We Would Stop At The Fractions, So Our Answer Ends Up Being 50.
Output What's Left As The Answer. Here's An Example: 103/3. First, Do Long Division. 103 - 90 = 13. 13 - 12 = 1. Now, As We Said, We Stop At The Fractions. So Instead Of Continuing The Process And Getting The Answer 34.3333333..., We Get 34. And Finally, We Output The Remainder, In This Case, 1.
NOTE: Some Mathematicians Write x mod y Instead Of x % y, But Most Programming Languages Only Understand %.

Smooth Coloring Mandelbrot Set Without Complex Number Library

I've coded a basic Mandelbrot explorer in C#, but I have those horrible bands of color, and it's all greyscale.
I have the equation for smooth coloring:
mu = N + 1 - log (log |Z(N)|) / log 2
Where N is the escape count, and |Z(N)| is the modulus of the complex number after the value has escaped, it's this value which I'm unsure of.
My code is based off the pseudo code given on the wikipedia page: http://en.wikipedia.org/wiki/Mandelbrot_set#For_programmers
The complex number is represented by the real values x and y, using this method, how would I calculate the value of |Z(N)| ?
|Z(N)| means the distance to the origin, so you can calculate it via sqrt(x*x + y*y).
If you run into an error with the logarithm: Check the iterations before. If it's part of the Mandelbrot set (iteration = max_iteration), the first logarithm will result 0 and the second will raise an error.
So just add this snippet instead of your old return code. .
if (i < iterations)
{
return i + 1 - Math.Log(Math.Log(Math.Sqrt(x * x + y * y))) / Math.Log(2);
}
return i;
Later, you should divide i by the max_iterations and multiply it with 255. This will give you a nice rgb-value.