I'm trying to make a function that approximates Cos(2) using the Maclaurin series approximation. So far I've made a 'Do' loop, but my approximation is off by -1.
My Function:
valX = 2
result = 0
numTerms = 5
i = 0
Do[
Print[
SetPrecision [
result =
result + (-1)^i*
(valX^(2*i)/Factorial[2*i]), 10]], {i, numTerms}]
Results:
-2.000000000
-1.333333333
-1.422222222
-1.415873016
-1.416155203 //decimal is correct but I'm off by -1.
Since Mathematica is 1-indexed, your Do[..., {i, numTerms}] loop ranges from 1 to numTerms. You probably want to go from 0 to numTerms. Try this, where the change is on the last line:
valX = 2
result = 0
numTerms = 5
i = 0
Do[
Print[
SetPrecision [
result =
result + (-1)^i*
(valX^(2*i)/Factorial[2*i]), 10]], {i, 0, numTerms}]
Actually I just figured it out. What has to happen is that I have to compensate for formula being recursive by subtracting from the exponent.
Correct Formula:
result =
result + (-1)^i-1*
(valX^(2*i-2)/Factorial[2*i-2])
The convergence is quicker too if you start expanding from Pi/2, i.e: valX=2-Pi/2 and the loop starts at i=1
Related
Say you have a vertical game board of length n (being the number of spaces). And you have a three-sided die that has the options: go forward one, stay and go back one. If you go below or above the number of board game spaces it is an invalid game. The only valid move once you reach the end of the board is "stay". Given an exact number of die rolls t, is it possible to algorithmically work out the number of unique dice rolls that result in a winning game?
So far I've tried producing a list of every possible combination of (-1,0,1) for the given number of die rolls and sorting through the list to see if any add up to the length of the board and also meet all the requirements for being a valid game. But this is impractical for dice rolls above 20.
For example:
t=1, n=2; Output=1
t=3, n=2; Output=3
You can use a dynamic programming approach. The sketch of a recurrence is:
M(0, 1) = 1
M(t, n) = T(t-1, n-1) + T(t-1, n) + T(t-1, n+1)
Of course you have to consider the border cases (like going off the board or not allowing to exit the end of the board, but it's easy to code that).
Here's some Python code:
def solve(N, T):
M, M2 = [0]*N, [0]*N
M[0] = 1
for i in xrange(T):
M, M2 = M2, M
for j in xrange(N):
M[j] = (j>0 and M2[j-1]) + M2[j] + (j+1<N-1 and M2[j+1])
return M[N-1]
print solve(3, 2) #1
print solve(2, 1) #1
print solve(2, 3) #3
print solve(5, 20) #19535230
Bonus: fancy "one-liner" with list compreehension and reduce
def solve(N, T):
return reduce(
lambda M, _: [(j>0 and M[j-1]) + M[j] + (j<N-2 and M[j+1]) for j in xrange(N)],
xrange(T), [1]+[0]*N)[-1]
Let M[i, j] be an N by N matrix with M[i, j] = 1 if |i-j| <= 1 and 0 otherwise (and the special case for the "stay" rule of M[N, N-1] = 0)
This matrix counts paths of length 1 from position i to position j.
To find paths of length t, simply raise M to the t'th power. This can be performed efficiently by linear algebra packages.
The solution can be read off: M^t[1, N].
For example, computing paths of length 20 on a board of size 5 in an interactive Python session:
>>> import numpy
>>> M = numpy.matrix('1 1 0 0 0;1 1 1 0 0; 0 1 1 1 0; 0 0 1 1 1; 0 0 0 0 1')
>>> M
matrix([[1, 1, 0, 0, 0],
[1, 1, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 1, 1],
[0, 0, 0, 0, 1]])
>>> M ** 20
matrix([[31628466, 51170460, 51163695, 31617520, 19535230],
[51170460, 82792161, 82787980, 51163695, 31617520],
[51163695, 82787980, 82792161, 51170460, 31628465],
[31617520, 51163695, 51170460, 31628466, 19552940],
[ 0, 0, 0, 0, 1]])
So there's M^20[1, 5], or 19535230 paths of length 20 from start to finish on a board of size 5.
Try a backtracking algorithm. Recursively "dive down" into depth t and only continue with dice values that could still result in a valid state. Propably by passing a "remaining budget" around.
For example, n=10, t=20, when you reached depth 10 of 20 and your budget is still 10 (= steps forward and backwards seemed to cancelled), the next recursion steps until depth t would discontinue the 0 and -1 possibilities, because they could not result in a valid state at the end.
A backtracking algorithms for this case is still very heavy (exponential), but better than first blowing up a bubble with all possibilities and then filtering.
Since zeros can be added anywhere, we'll multiply those possibilities by the different arrangements of (-1)'s:
X (space 1) X (space 2) X (space 3) X (space 4) X
(-1)'s can only appear in spaces 1,2 or 3, not in space 4. I got help with the mathematical recurrence that counts the number of ways to place minus ones without skipping backwards.
JavaScript code:
function C(n,k){if(k==0||n==k)return 1;var p=n;for(var i=2;i<=k;i++)p*=(n+1-i)/i;return p}
function sumCoefficients(arr,cs){
var s = 0, i = -1;
while (arr[++i]){
s += cs[i] * arr[i];
}
return s;
}
function f(n,t){
var numMinusOnes = (t - (n-1)) >> 1
result = C(t,n-1),
numPlaces = n - 2,
cs = [];
for (var i=1; numPlaces-i>=i-1; i++){
cs.push(-Math.pow(-1,i) * C(numPlaces + 1 - i,i));
}
var As = new Array(cs.length),
An;
As[0] = 1;
for (var m=1; m<=numMinusOnes; m++){
var zeros = t - (n-1) - 2*m;
An = sumCoefficients(As,cs);
As.unshift(An);
As.pop();
result += An * C(zeros + 2*m + n-1,zeros);
}
return result;
}
Output:
console.log(f(5,20))
19535230
I need help optimizing this loop. matrix_1 is a (nx 2) int matrix and matrix_2 is a (m x 2), m & n very.
index_j = 1;
for index_k = 1:size(Matrix_1,1)
for index_l = 1:size(Matrix_2,1)
M2_Index_Dist(index_j,:) = [index_l, sqrt(bsxfun(#plus,sum(Matrix_1(index_k,:).^2,2),sum(Matrix_2(index_l,:).^2,2)')-2*(Matrix_1(index_k,:)*Matrix_2(index_l,:)'))];
index_j = index_j + 1;
end
end
I need M2_Index_Dist to provide a ((n*m) x 2) matrix with the index of matrix_2 in the first column and the distance in the second column.
Output example:
M2_Index_Dist = [ 1, 5.465
2, 56.52
3, 6.21
1, 35.3
2, 56.52
3, 0
1, 43.5
2, 9.3
3, 236.1
1, 8.2
2, 56.52
3, 5.582]
Here's how to apply bsxfun with your formula (||A-B|| = sqrt(||A||^2 + ||B||^2 - 2*A*B)):
d = real(sqrt(bsxfun(#plus, dot(Matrix_1,Matrix_1,2), ...
bsxfun(#minus, dot(Matrix_2,Matrix_2,2).', 2 * Matrix_1*Matrix_2.')))).';
You can avoid the final transpose if you change your interpretation of the matrix.
Note: There shouldn't be any complex values to handle with real but it's there in case of very small differences that may lead to tiny negative numbers.
Edit: It may be faster without dot:
d = sqrt(bsxfun(#plus, sum(Matrix_1.*Matrix_1,2), ...
bsxfun(#minus, sum(Matrix_2.*Matrix_2,2)', 2 * Matrix_1*Matrix_2.'))).';
Or with just one call to bsxfun:
d = sqrt(bsxfun(#plus, sum(Matrix_1.*Matrix_1,2), sum(Matrix_2.*Matrix_2,2)') ...
- 2 * Matrix_1*Matrix_2.').';
Note: This last order of operations gives identical results to you, rather than with an error ~1e-14.
Edit 2: To replicate M2_Index_Dist:
II = ndgrid(1:size(Matrix_2,1),1:size(Matrix_2,1));
M2_Index_Dist = [II(:) d(:)];
If I understand correctly, this does what you want:
ind = repmat((1:size(Matrix_2,1)).',size(Matrix_1,1),1); %'// first column: index
d = pdist2(Matrix_2,Matrix_1); %// compute distance between each pair of rows
d = d(:); %// second column: distance
result = [ind d]; %// build result from first column and second column
As you see, this code calls pdist2 to compute the distance between every pair of rows of your matrices. By default this function uses Euclidean distance.
If you don't have pdist2 (which is part of the the Statistics Toolbox), you can replace line 2 above with bsxfun:
d = squeeze(sqrt(sum(bsxfun(#minus,Matrix_2,permute(Matrix_1, [3 2 1])).^2,2)));
please can you help me with creation of function in Wolfram Mathematica for magic square. I must create function MagicSquare[n_], which output is sqare matrix of first n^2 integers, and sum of these integers in every column, every row, and on diagonals must be the same. Please help me, I try this for a days and I failed. I need this for my school assignment.
Here is a simple brute-force approach. Note the check value m is the magic constant.
(Setting the random values to the array variables makes nifty use of HoldFirst.)
n = 3;
m = n (n^2 + 1)/2;
check = {0};
While[Unequal[Union[check], {m}],
Clear[s];
x = Table[s[i, j], {i, 1, n}, {j, 1, n}];
d1 = Diagonal[x];
d2 = Diagonal[Reverse[x]];
cols = Transpose[x];
vars = Flatten[x];
rand = RandomSample[Range[n^2], n^2];
MapThread[Function[{v, r}, v = r, HoldFirst], {vars, rand}];
check = Total /# Join[x, cols, {d1, d2}]];
MatrixForm[x]
8 3 4
1 5 9
6 7 2
Here is another brute force approach that works for n=3 ..
n = 3
m = n (n^2 + 1) /2
Select[
Partition[# , n] & /#
Permutations[Range[n^2]],
(Union #(Total /# # )) == {m} &&
(Union #(Total /# Transpose[#] )) == {m} &&
Total#Diagonal[#] == m &&
Total#Diagonal[Reverse##] == m & ][[1]] // MatrixForm
This has the advantage of immediately producing an out of memory error for larger n, while Chris' will run approximately forever. :)
I am a new user of Mathematica and I can't figure out how to solve this problem.
I have a computation S that gives me for 10 Random Variates 10 results:
Xi = RandomVariate[NormalDistribution[], 10]
Mu = -0.00644131
Sigma= 0.0562005
t = 0.1
s = 100
fnmc[s_,Mu_,Sigma_, t_,Xi_] := s Exp[(Mu - Sigma^2/2) t + Sigma Sqrt[t ] Xi]
S = fnmc[s, Mu, Sigma, t, Xi]
Now I need to compute formula S 10 times - so I'll have 100 numbers in result.
I can't find the way to do it in a TABLE. Further, I will have to sum those 10 results and calculate Mean etc. I wanted to use TABLE because of the further computation - SUM, MEAN - I thought it is the easiest "form" of results to work with....is it?
I had in mind something like:
Table[S(i),{i,10}]
but off course it multiplies S x (i). Any suggestions?
S(i) multiplies S with i. S[i] calls function S with parameter i.
The four kinds of bracketing in Mathematica
I just realized that S isn't a function at all, so you don't want to call it with parameter i. You can get the result of S 10 times simply by Table[S,{10}], but since Xi is only calculated once, this will just give you 10 times the same vector. Maybe you want to do the whole calculation 10 times? That would be:
Table[
(
Xi = RandomVariate[NormalDistribution[], 10];
Mu = -0.00644131;
Sigma = 0.0562005;
t = 0.1; s = 100;
s*Exp[(Mu - Sigma^2/2)*t + Sigma*Sqrt[t]*Xi]
), {10}]
You could use a functional programming approach map ( /# ) your function over the Xis you've created.
Mu = -0.00644131;
Sigma= 0.0562005;
t = 0.1;
s = 100;
(* if you wanted ten scalar random numbers, with each one used on one application of your equation *)
Xi = RandomVariate[NormalDistribution[], 10];
ans = s Exp[(Mu - Sigma^2/2) t + Sigma Sqrt[t ] #] & /# Xi;
(* if you wanted ten 10 dimensional random numbers, with each 10D number used on one application of your equation *)
Xi = RandomVariate[NormalDistribution[], {10,10}];
ans = s Exp[(Mu - Sigma^2/2) t + Sigma Sqrt[t ] #] & /# Xi;
I am working on an algorithm which calculates the determinant of any n*n matrix, here is my code:
Laplace[matrix_List] := Module[{a = matrix, newmatrix, result = 0},
If [Length[a] == 1, result = Total[Total[a]],
For [i = 1, i <= Length[a], i++,
newmatrix = Drop[a, {i}, {1}];
result = result + (-1)^(i + 1) *
Total[Total[Take[a, {i}, {1}]]]*
Laplace[newmatrix];
]
]; result]
It works recursively, it works for a 2*2 matrix(I have checked with Det[]),
but it doesn't work for any matrix of higher degree than 2!
I would like to solve this solution myself - I want to implement this myself, rather than simply using Det - but I would appreciate it if someone could explain what is wrong with the recursion here?
You should not calculate the determinant in a recursive way, it takes a lot of time. The simplest method is to take the first column and see if there is an element different from 0. If there isn't then the determinant is equal to 0. Otherwise take that element and for every line in the matrix different from that of the chosen element substract the line of the chosen element multiplied with the symetric of the first element of the current line. That substraction should leave you with a line which has 0 as its first element. Then you can eliminate the first column and the line of the chosen element and multiply the n-1 order determinant with (-1)^(line_index+column_index)*chosen_element.
mat = {{a11,a12,a13,a14]}, {a21,a22,a23,a24}, {a31,a32,a33,a34}, {a41,a42,a43,a44}};
det = Sum[Signature[p[[j]]]*
Product[mat[[i, p[[j, i]]]], {i, 1, Length[mat]}], {j, 1, 4!}]
this will produce a correct result! det===Det[mat]
Good Luck