How to calculate number of rectangles in rectangular grid? - math

I want to calculate number of rectangles in a rectangles.It can be done using formula
(x^2+x)(y^2+y)/4
but it also includes perfect squares like 1*1,2*2,3*3 etc.I dont want to include that in my calculations.How can i do that?

Ok, you have the number of rectangles with integer coordinates between the points (0, 0), (x, 0), (x, y) and (0, y), x and y being integers too. You now need to remove the perfect squares from this sum.
To compute it, let's evaluate the number of squares 1*1: there are obviously x*y of them. For squares 2*2, we have x-1 choices for the x-coordinate and y-1 for the y-coordinate of the bottom left-hand corner of such a square, due to the width of this square: this results in (x-1)*(y-1) squares. Idem, we will have (x-2)*(y-2) squares 3*3, etc.
So for a given i, we have (x - i + 1) * (y - i + 1) squares i*i, and i goes from 1 to the minimum of x and y (of course if x is 4 and y is 7, we cannot have a square with a side greater than 4).
So if m = min(x, y), we have:
Sum_Squares = Sum(i = 1, i = m, (x - i + 1) * (y - i + 1))
= Sum(j = 0, j = m - 1, (x - i) * (y - i))
= Sum(j = 0, j = m - 1, x*y - (x+y)*j + j^2)
= m*x*y - (x+y)*Sum(j = 0, j = m - 1, j) + Sum(j = 0, j = m - 1, j^2)
= m*x*y - (x+y)*Sum(j = 1, j = m - 1, j) + Sum(j = 1, j = m - 1, j^2)
= m*x*y - (x+y)*m*(m-1)/2 + (m-1)*m*(2*m-1)/6
I get that with an index change (j = i - 1) and via the well-known formulas:
Sum(i = 1, i = n, j) = n*(n + 1)/2
Sum(i = 1, i = n, j^2) = n*(n + 1)*(2*n + 1)/6
You just have to remove this Sum_Squares from (x^2+x)(y^2+y)/4 and you're done !

Related

Moving average (and rolling mean) using `stats::filter`

I am learning to calculate moving averages in R with this code:
x <- rnorm(n = 100, mean = 0, sd = 10)
mn <- function(n) rep (1 / n, n)
y <- filter(x, mn(5))
When I plot only mn(5), I see that 1/5 is repeated 5 times. My questions are:
Why using filter(x, mn(5)) calculates the average of the five values?
What part of x is averaged?
What part of x is averaged?
See ?filter for argument sides. The default value sides = 2 means "center". You probably want sides = 1 to use past values only.
In general,
y <- filter(x, c(w1, w2, w3, w4, w5), sides = 1)
computes:
y[1:4] = NA
y[5] = w1 * x[5] + w2 * x[4] + w3 * x[3] + w4 * x[2] + w5 * x[1]
y[6] = w1 * x[6] + w2 * x[5] + w3 * x[4] + w4 * x[3] + w5 * x[2]
## and etc.
Why using filter(x, mn(5)) calculates the average of the five values?
In this particular case:
y <- filter(x, c(1/5, 1/5, 1/5, 1/5, 1/5), sides = 1)
computes:
y[1:4] = NA
y[5] = (x[5] + x[4] + x[3] + x[2] + x[1]) / 5 = mean(x[5:1])
y[6] = (x[6] + x[5] + x[4] + x[3] + x[2]) / 5 = mean(x[6:2])
## and etc.
which gives rolling mean.
Remark:
Moving average is much more general than rolling mean. Another way to compute simple rolling mean is
zoo::rollmean(x, k = 5, na.pad = TRUE, align = "right")
There is also an R package called RcppRoll.
1) The mean is the average of the values so assuming x has 5 elements we can write the second line and that is the same as the third line and the fourth line so using coefficients of (1/5, 1/5, 1/5, 1/5, 1/5) in the sum is equivalent to taking the mean.
mean(x)
= (x[1] + x[2] + x[3] + x[4] + x[5])/5
= x[1]/5 + x[2]/5 + x[3]/5 + x[4]/5 + x[5]/5
= sum(x * c(1/5, 1/5, 1/5, 1/5, 1/5))
2) Another way to understand this is to note that mean is linear. That is if x and y are two vectors of the same length then mean(x+y) = mean(x) + mean(y) and if a is any scalar then mean(a * x) = a * mean(x). Now it is known that any linear function that returns a scalar is representable as the inner product of some vector times the input. That is there is a vector v such that
mean(x)
sum(v * x)
are equal for all x. Now since it is true for all x it must be true for x <- c(1, 0, 0, 0, 0) so these are equal
mean(c(1, 0, 0, 0, 0)
v[1] * x[1]
but the second line equals v[1] since x[1] is 1 and the mean of c(1, 0, 0, 0, 0) in the first line equals 1/5 and similarly for
mean(c(0, 1, 0, 0, 0))
v[2] * x[2]
etc. so v must equal c(1/5, 1/5, 1/5, 1/5, 1/5).

With 3 points, how do I calculate the offset of the plane they form

I have a triangle of 3 points A, B, and C.
I can find the normal of the triangle just fine by doing
|AB x AC|
In the below picture, it shows ABC that I know and |n1| which I can calculate. But how would I find P1?
If it helps, I need to use it to know if a Ray will collide with a Convex Mesh and it requires P1. Using A, B, or C, it seems to not work.
Vector P1 = (D*a1 + D*b1 + D*c1) should be perpendicular to vector (P1-C) (use any point from A,B,C), so dot product is zero
D * a1 * (D * a1 - cx) + D * b1 * (D * b1 - cy) + D * c1* (D * c1 - cz) = 0
or
D = (N.dot.C) / (a1^2 + b1^2 + c1^2)
If normal is unit (normalized), then expression for coefficient D becomes very simple
d = uN.dot.C
After that:
P1 = D * N = d * uN
Quick check:
A = (2, 0, 0)
B = (2, 2, 0)
C = (2, 0, 2)
AB = (0, 2, 0)
AC = (0, 0, 2)
N = AB x AC = (4, 0, 0)
N.dot.N = 16
uN = (1, 0, 0)
N.dot.C = (4 * 2) = 8
D = N.dot.C / N.dot.N = 1/2
P1 = D * N = (2, 0, 0)
d = uN.dot.C = (1 * 2) = 2
P1 = d * uN = (2, 0, 0)
The general equation for any plane is
Ax + By + Cz + D = 0
where (A, B, C) is a normal vector to the plane, that you have already calculated with three points.
To get D just substitute x,y,z with the coordinates of any point (x1,y1,z1) you know to be in the plane:
D = -(A*x1 + B*y1 + C*z1)
The good new is that if vector (A,B,C) is a unit vector, then |D| is the distance from the origin (perpendicular) to the plane.

Binomial Tree Plot in R

I have a little issue with the binomial tree plot in R; I'm using the package fOptions. Given St=39, K=40, T1=0.5, r=0.02, sigma=0.2, n=2, I use the following code:
CRRTree<- BinomialTreeOption(TypeFlag='ce',39,40,0.5,0.02,0.02,0.2,2)
BinomialTreePlot(CRRTree)
and the corresponding plot is
I have two problems.
First: I want that the x axis starts from zero and goes to 2
Second: I don't undestand why the upper value of the tree is not showed in the picture; how can I fix it?
Thank you very much.
EDIT: I solved the second problem in the easiest way, I think. It was sufficient to code the plot in this way:
BinomialTreePlot(CRRTree,ylim=c(-2,2.5))
There is an easy way to solve also the problem of making the tree starts from 0?
You will have to modify the code for the BinomialTreePlot function. For example, you could try something like that:
my_BinomialTreePlot<-function (BinomialTreeValues, dx = -0.025, dy = 0.4, cex = 1,
digits = 2, ...)
{
Tree = round(BinomialTreeValues, digits = digits)
depth = ncol(Tree)
plot(x = c(0, depth-1), y = c(-depth + 1, depth - 1), type = "n",
col = 0, ...)
points(x = 0, y = 0)
text(0 + dx, 0 + dy, deparse(Tree[1, 1]), cex = cex)
for (i in 1:(depth - 1)) {
y = seq(from = -i, by = 2, length = i + 1)
x = rep(i, times = length(y)) + 0
points(x, y, col = 1)
for (j in 1:length(x)) text(x[j] + dx, y[j] + dy, deparse(Tree[length(x) +
1 - j, i + 1]), cex = cex)
y = (-i):i
x = rep(c(i, i-1), times = 2 * i)[1:length(y)]
lines(x, y, col = 2)
}
invisible()
}
Then use it like this:
CRRTree<- BinomialTreeOption(TypeFlag='ce',39,40,0.5,0.02,0.02,0.2,2)
my_BinomialTreePlot(CRRTree,xlim=c(-0.1,2), ylim=c(-2.5,2.5))

Calculating position of object based on number of objects

I have a simple question but am having a hard time coming up with an elegant solution.
Let's say that my app displays a deck of cards. Each time I draw a card, I want to display it in the center of the screen. When I draw a new card, I want to display that card next to the previous one and both be centered.
So more specifically if my code had the following variables and tables
N = total cards played. Assume N is between 1 and 10.
W = width to separate each card in pixels. For example 30px
C = width of screen / 2 ( center x value for the screen )
P = {} -- which denotes the position of the card and it's new X value. P[1] will be the x value for the first card played.
I want a formula so I can run a loop and calculate the new X value for each card.
Here is my expected output
N = 1, P[1] = C. If there is only 1 card, then the x value of that card will be the center
N = 2, P[1] = C - W/2, P[2] = C + W/2
N = 3, P[1] = C - W, P[2] = C, P[3] = C + W
N = 4, P[1] = C - 3/2 * W, P[2] = C - 1/2 * W, P[3] = C + 1/2 * W, P[4] = C + 3/2 * W
So I need a loop which programatically calculates this for me. Not sure how to do it.
This formula should do the trick:
P[k] = C + W * (k - 1 - (N - 1) / 2)
where k = 1,2,...,N is the number of the card.
The various cases are:
N = 1 => P[k] = C + W * (k - 1)
=> P[1] = C
N = 2 => P[k] = C + W * (k - 1 - 1/2)
=> P[1] = C - W/2, P[2] = C + W/2
N = 3 => P[k] = C + W * (k - 1 - 1)
=> P[1] = C - W, P[2] = C, P[3] = C + W
N = 4 => P[k] = C + W * (k - 1 - 3/2)
=> P[1] = C - 3W/2, P[2] = C - W/2, P[3] = C + W/2, P[4] = C + 3W/2
...
You can wrap the formula in a nifty function, as in the following test program, which produces more or less the same scheme above:
local C = 10
local W = 20
local function CardPosition( k, N )
return C + W * (k - 1 - (N - 1) / 2)
end
for N = 1, 5 do
io.write( "N = ", N, " => P[k] = ",
C, " + ", W, " * (k - 1 - ", N - 1, "/2) \n" )
io.write " => "
for k = 1, N do
io.write( "P[", k,"] = ", CardPosition(k, N), ", " )
end
io.write "\n\n"
end
You can easily spot that P[1] = C - (N-1)/2 * W in the cases you described. This is generally true, because the total width increases linearly with the number of cards.
Other cards' positions can be computed with the help of the expression: P[x] = P[x-1] + W.

2 Dimension Runge-Kutta Method on Mathematica 8

I have a problem while programing in Mathematica 8, here is my code:
f[t_, y_] := {y, y};
RungeKutta3[a_, b_, Alpha_, n_, f_] :=
Module[{h, j, k1, k2, k3},
h = (b - a)/n;
Y = T = Table[0, {100 + 1}];
Y[[1]] = Alpha;
T[[1]] = a;
For[j = 1, j <= n, ++j,
k1 = f[T[[j]], Y[[j]]];
k2 = f[T[[j]] + h/2, Y[[j]] + k1*h/2];
k3 = f[T[[j]] + h, Y[[j]] + (-k1 + 2 k2)h];
Y[[j + 1]] = Y[[j]] + h/6(k1 + 4 k2 + k3);
(* Print[j, "----->", Y[[j]]];*)
T[[j + 1]] = T[[j]] + h;
];];
RungeKutta3[0., 1., {300., 500}, 2, f];
The thing is, I'm trying to implement a Runge-Kutta method. And I was successful actually, but only with a function f[x_] that had 1 dimension. This code is for 2 dimensions, but it simply doesn't work and I don't know why. Here is an example for a code with 1 dimension only (notice that I have to change the first line to define the function and the last line, when I call "RungeKutta3").
f[t_, y_] := y;
RungeKutta3[a_, b_, Alpha_, n_, f_] :=
Module[{h, j, k1, k2, k3},
h = (b - a)/n;
Y = T = Table[0, {100 + 1}];
Y[[1]] = Alpha;
T[[1]] = a;
For[j = 1, j <= n, ++j,
k1 = f[T[[j]], Y[[j]]];
k2 = f[T[[j]] + h/2, Y[[j]] + k1*h/2];
k3 = f[T[[j]] + h, Y[[j]] + (-k1 + 2 k2)*h];
Y[[j + 1]] = Y[[j]] + h/6*(k1 + 4 k2 + k3);
(* Print[j, "----->", Y[[j]]];*)
T[[j + 1]] = T[[j]] + h;
];];
RungeKutta3[0., 1., 300., 100, f];
To sum up, how do I implemented the Runge-Kutta method for a function with 2 dimensions??
If you could help me out I would be grateful.
Thanks in advance!
PS: the Runge-Kutta method is order 3
----------------------
Problem solved! Check the code, if anybody needs help with anything, just ask!
f[t_, y1_, y2_] := 3 t*y2 + Log[y1] + 4 y1 - 2 t^2 * y1 - Log[t^2 + 1] - t^2;
F[t_, {y1_, y2_}] := {y2, f[t, y1, y2]};
RungeKutta3[a_, b_, [Alpha]_, n_, f_] :=
Module[{h, j, k1, k2, k3, Y, T, R},
h = (b - a)/n;
Y = T = Table[0, {n + 1}];
Y[[1]] = [Alpha]; T[[1]] = a;
For[j = 1, j <= n, ++j,
k1 = f[T[[j]], Y[[j]]];
k2 = f[T[[j]] + h/2, Y[[j]] + k1*h/2];
k3 = f[T[[j]] + h, Y[[j]] + (-k1 + 2 k2)*h];
Y[[j + 1]] = Y[[j]] + h/6*(k1 + 4 k2 + k3);
T[[j + 1]] = T[[j]] + h;
];
R = Table[0, {n + 1}];
For[j = 1, j <= n + 1, j++, R[[j]] = Y[[j]][[1]]];
Print[ListPlot[Transpose[{T, R}]]]
];
RungeKutta3[0., 1, {1., 0.}, 1000, F];
I know basically have a mathematica program that can solve ANY 2nd order equation! Through Runge-Kutta method. just insert your function on
f[t_, y1_, y2_]:= [Insert your function here]
where t is the independent value, y1 is the function itself y(t), y2 is y'(t).
Call the function through:
RungeKutta3[a, b, [Alpha], n, F];
where a is the initial "t" value, b the final "t" value, [Alpha] the initial value of your function and the first derivative (given in the form {y1(a),y2(a0)}), n the number of points equally spaced you want to represent. F is the function you have to insert despite of the function you give to f
Any questions feel free to ask!!
PS: The Runge-Kutta problem solves differential equations with problems of initial values, i used this program as a base to solve a problem of boundary values, if you want it just text me!
Doesn't your code just implement what is already built into Mathematica, namely, if you were to use the option
Method -> {"ExplicitRungeKutta", "DifferenceOrder" -> 3}
to NDSolve?
(This is not to suggest there's no value in "rolling your own": perhaps you want to do it as a learning exercise for yourself or for students, or as a student yourself.)

Resources