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.)
Related
What is the most numerically stable way of calculating:
log[(wx * exp(x) + wy * exp_y)/(wx + wy)]
where the weights wx, wy > 0?
Without the weights, this function is logaddexp and could be implemented in Python with NumPy as:
tmp = x - y
return np.where(tmp > 0,
x + np.log1p(np.exp(-tmp)),
y + np.log1p(np.exp(tmp)))
How should I generalize this to the weighted version?
You could use the original logaddexp function for thus purpose, if you rewrite the weighted expression as,
This is equivalent to,
logaddexp( x + log(w_x), y + log(w_y) ) - log(w_x + w_y)
which should be as numerically stable as the original logaddexp implementation.
Note: I'm referring to the numpy.logaddexp function that takes in x and y, not x and exp_y, as you mention in the question.
def weighted_logaddexp(x, wx, y, wy):
# Returns:
# log[(wx * exp(x) + wy * exp_y)/(wx + wy)]
# = log(wx/(wx+wy)) + x + log(1 + exp(y - x + log(wy)-log(wx)))
# = log1p(-wy/(wx+wy)) + x + log1p((wy exp_y) / (wx exp(x)))
if wx == 0.0:
return y
if wy == 0.0:
return x
total_w = wx + wy
first_term = np.where(wx > wy,
np.log1p(-wy / total_w),
np.log1p(-wx / total_w))
exp_x = np.exp(x)
exp_y = np.exp(y)
wx_exp_x = wx * exp_x
wy_exp_y = wy * exp_y
return np.where(wy_exp_y < wx_exp_x,
x + np.log1p(wy_exp_y / wx_exp_x),
y + np.log1p(wx_exp_x / wy_exp_y)) + first_term
Here's how I compared the two solutions:
import math
import numpy as np
import mpmath as mp
from tools.numpy import weighted_logaddexp
def average_error(ideal_function, test_function, n_args):
x_y = [np.linspace(0.1, 3, 20) for _ in range(n_args)]
xs_ys = np.meshgrid(*x_y)
def e(*args):
return ideal_function(*args) - test_function(*args)
e = np.frompyfunc(e, n_args, 1)
error = e(*xs_ys) ** 2
return np.mean(error)
def ideal_function(x, wx, y, wy):
return mp.log((mp.exp(x) * wx + mp.exp(y) * wy) / mp.fadd(wx, wy))
def test_function(x, wx, y, wy):
return np.logaddexp(x + math.log(wx), y + math.log(wy)) - math.log(wx + wy)
mp.prec = 100
print(average_error(ideal_function, weighted_logaddexp, 4))
print(average_error(ideal_function, test_function, 4))
It's a homework question and has to be solved using Dyanmic Programming approach.
What I've managed to do so far is that:
Let f(x) denote the number of times x can be written:
Then f(x) = f(x - 1) + 1 ; f(5) = f(4) + 1 (5 = 4 + 1)
But I don't think this is the right approach. Anybody would like to help?
An example of what the problem really is:
Number of ways 4 can be written:
4: 3 + 1
4: (2 + 1) + 1
4: 2 + 2
4: (1 + 1) + (1 + 1)
this representation is call partition. it could be solved in different ways.
for example, let's say
f(x, m) - number of partitions of x
such that the largest number in that partition is m
then
f(x, m) = sum of all f(x - m, k) where (1 <= k <= m),
also (k<=x-m), because f(x, y) = 0 where (y > x)
for your example ( let's count the number itself a partition also (f(x, x) = 1))
f(1, 1) = 1
f(2, 1) = f(1, 1) = 1
f(2, 2) = 1
f(3, 1) = f(2, 1) = 1
f(3, 2) = f(1, 1) = 1 //+ f(1, 2) zero
f(4, 1) = f(3, 1) = 1
f(4, 2) = f(2, 1) + f(2, 2) = 2
f(4, 3) = f(1, 1) = 1 // + f(1, 2) + f(1, 3) zeroes
f(4, 4) = 1
so the sum of f(4, 1), f(4, 2), f(4, 3), f(4, 4) = 5 ( 4 if not count 4 itself a partition)
I am absolutely stumped on this one.
T(n) = { 3, if n = 2 || T(n - 1) + (n/4), if n > 2
Prove by induction that T(n) = (n^2 + n + 18) / 8 [V n >= 2]
I know how to execute a proof by induction, but for some reason I cannot solve this expression for the k + 1 case.
Any help would be most excellent.
First, we choose n = 2:
T(n = 2) = (2^2 + 2 + 18) / 8 = 24 / 8 = 3
Great, that works. Now we know that there is a number k >= 2 that fulfills the definition of T(n). Then, let's set n = k+1 for an arbitrary k >= 2:
T(n = k+1) = ((k+1)^2 + k + 1 + 18) / 8
= (k^2 + 2k + 1 + k + 1 + 18) / 8
= (k^2 + k + 18) / 8 + (2 + 2k) / 8
= T(k) + k/4
That is exactly what the definition of T(n) says.
∎
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.
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 !