I have the code to solve a problem of non-stationary heat transfer (no, this is not homework, but the code is taken from a textbook), which requires solving a set of ODEs with the Method of Lines, and goes as follows:
%Problem P6_08A
clear, clc, format short g, format compact
tspan = [0 1000.]; % Range for the independent variable
y0 = [100.; 100.; 100.; 100.; 100.; 100.; 100.; 100.; 100.]; % Initial values for the dependent variables
%- - - - - - - - - - - - - - - - - - - - - -
function dYfuncvecdt = ODEfun(Yfuncvec, t);
Yfuncvec = [];
T2 = Yfuncvec(1);
T3 = Yfuncvec(2);
T4 = Yfuncvec(3);
T5 = Yfuncvec(4);
T6 = Yfuncvec(5);
T7 = Yfuncvec(6);
T8 = Yfuncvec(7);
T9 = Yfuncvec(8);
T10 = Yfuncvec(9);
alpha = .00002;
deltax = .1;
T1 = 0;
T11 = (4 * T10 - T9) / 3;
dT2dt = alpha / (deltax ^ 2) * (T3 - (2 * T2) + T1);
dT3dt = alpha / (deltax ^ 2) * (T4 - (2 * T3) + T2);
dT4dt = alpha / (deltax ^ 2) * (T5 - (2 * T4) + T3);
dT5dt = alpha / (deltax ^ 2) * (T6 - (2 * T5) + T4);
dT6dt = alpha / (deltax ^ 2) * (T7 - (2 * T6) + T5);
dT7dt = alpha / (deltax ^ 2) * (T8 - (2 * T7) + T6);
dT8dt = alpha / (deltax ^ 2) * (T9 - (2 * T8) + T7);
dT9dt = alpha / (deltax ^ 2) * (T10 - (2 * T9) + T8);
dT10dt = alpha / (deltax ^ 2) * (T11 - (2 * T10) + T9);
dYfuncvecdt = [dT2dt; dT3dt; dT4dt; dT5dt; dT6dt; dT7dt; dT8dt; dT9dt; dT10dt];
end
%
[y, t]=lsode(#ODEfun, y0,tspan);
disp([y0 ODEfun(tspan(1),y0)]);
disp(' Variable values at the initial point ');
disp([' t = ' num2str(tspan(1))]);
disp(' y dy/dt ');
for i=1:size(y,2)
disp([' Solution for dependent variable y' int2str(i)]);
disp([' t y' int2str(i)]);
disp([t y(:,i)]);
plot(t,y(:,i));
title([' Plot of dependent variable y' int2str(i)]);
xlabel(' Independent variable (t)');
ylabel([' Dependent variable y' int2str(i)]);
pause
end
%EOF
Trying to run the code returns an error:
error: ODEfun: A(I): index out of bounds; value 1 out of bound 0
error: called from:
error: ODEfun at line 8, column 4
error: lsode: evaluation of user-supplied function failed
error: lsode: inconsistent sizes for state and derivative vectors
error: $path/lines01_diff_eq.m at line 33, column 5
It is the part index out of bounds; value 1 out of bound 0 that I can't make sense of. Can somebody help?
It turns out that that line:
disp([y0 ODEfun(tspan(1),y0)]);
Should instead become:
disp([y0 ODEfun(y0, tspan(1)]);
And also the lines:
disp([t y(:,i)]);
plot(t,y(:,i));
Should be modified to:
disp([tspan y(:,i)']);
plot(tspan, y(:,i)');
In order to make the code execute without errors.
Related
I tried to run this function in MATLAB:
function llik = log_likelihood(p)
global d;
N = length(d);
tau = fzero(#(t) (t - (t^2 * p + 1 - p) / (2 * (t * p + 1 - p))), [0,1]);
loglik = 0;
for i = 1 : N
loglik = loglik + log(isnan(d(i)) * (1 - p * (1 - tau) + ~isnan(d(i))* p * (1 - tau)));
end
llik = loglik / N;
end
Here, p is a scalar. MATLAB gives me an error warning saying
Error using fzero>localFirstFcnEval
FZERO cannot continue because user-supplied function_handle ==>
#(t)(t-(t^2*p+1-p)/(2*(t*p+1-p))) failed with the error below.
Unrecognized function or variable 'p'.
I am confused since p should be the argument of the function. How can it be unrecongized? Thank you for your help!
Everything seems okay with my Matlab if i assign the value d inside the function, where do you define the variable d, if it's a global variable, it must be define as:
global d;
This is my result:
I am trying to calculate the momentum matrix element between the ground and first excited vibrational states for a harmonic oscillator using the Fourier transform of the eigenfunctions in position space. I am having trouble calculating the momentum matrix element correctly.
Here is my code
hbar = 1
nPoints = 501
xmin = -5
xmax = 5
dx = (xmax - xmin) / nPoints
x = np.array([(i - nPoints // 2) * dx for i in range(nPoints)])
potential = np.array([0.5 * point**2 for point in x]) # harmonic potential
# get eigenstates, eigenvalues with Fourier grid Hamiltonian approach
energies, psis = getEigenstatesFGH(x, potential, mass=1, hbar=hbar)
# should be 0.5, 1.5, 2.5, 3.5, 4.5 or very close to that
for i in range(5):
print(f"{energies[i]:.2f}")
# identify the necessary wave functions
groundState = psis[:, 0]
firstExcitedState = psis[:, 1]
# fourier transform the wave functions into k-space (momentum space)
dp = (2 * np.pi) / (np.max(x) - np.min(x))
p = np.array([(i - nPoints // 2) * dp for i in range(nPoints)])
groundStateK = (1 / np.sqrt(2 * np.pi * hbar)) * np.fft.fftshift(np.fft.fft(groundState))
firstExcitedStateK = (1 / np.sqrt(2 * np.pi * hbar)) * np.fft.fftshift(np.fft.fft(firstExcitedState))
# calculate matrix elements
xMatrix = np.eye(nPoints) * x
pMatrix = np.eye(nPoints) * p
# <psi0 | x-hat | psi1 >, this works correctly
x01 = np.dot(np.conjugate(groundState), np.dot(xMatrix, firstExcitedState))
# <~psi0 | p-hat | ~psi1 >, this gives wrong answer
p01 = np.dot(np.conjugate(groundStateK), np.dot(pMatrix, firstExcitedStateK))
I've installed and loaded the symbolic package that becomes available from optim package to obtain the syms function (like in MATLAB) but when I use solve() function the command window goes in Waiting mode like
Waiting..........
My code is given below:
syms s T K D1 D2 D3 theta1 theta2 theta3 J1 J2 J3
eq1 = (s * D1 + K + J1 * s ^ 2)* theta1 - K * theta2 == T;
eq2 = -K * theta1 + (J2 * s ^ 2 + K + D2 * s) * theta2 - D2 * s * theta3 == 0;
eq3 = -D2 * s * theta2 + (D3 * s + J3 * s ^ 2 + D2 * s) * theta3 == 0;
S = solve(eq1, eq2, eq3)
but if I manually solve it by inverse method, it gives the answer instantly. Kindly help to solve this bug.
Rate Formula is not working as expected for big values...
RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0) in physical file it returns 0.05819488005
if the same formula we tried to set through POI returns 0.009056339275922086..
Even we tried to save the excel and open same 0.009056339275922086 is returned..
Code used to set in POI :
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFRow row = sheet.createRow(1);
XSSFCell cell = row.createCell(1);
cell.setCellType(CellType.NUMERIC);
cell.setCellFormula("RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0)");
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
evaluator.evaluateInCell(cell);
cell.getNumericCellValue();
The Rate function of apache poi states that it "// find root by Newton secant method". That's nonsense since Secant method is only a Quasi-Newton method. And "If the initial values are not close enough to the root, then there is no guarantee that the secant method converges.".
So the default guess of 0.1 seems not "close enough" and so if we are using cell.setCellFormula("RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0, 0, 0.06)"); - note the explicit setting of type and guess properties and having the guess property "close enough" to the result of 0.05819488005- then the formula evaluates properly.
If apache poi really would use Newton's method, then the function would evaluate properly also using the default guess of 0.1. The disadvantage of Newton's method is that it requires the evaluation of both f and its derivative f′ at every step. So it may be slower than the Secant method in some cases.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
public class ExcelRATEFunction {
private static double calculateRateNewton(double nper, double pmt, double pv, double fv, double type, double guess) {
int FINANCIAL_MAX_ITERATIONS = 20;
double FINANCIAL_PRECISION = 0.0000001;
double y, y1, xN = 0, f = 0, i = 0;
double rate = guess;
//find root by Newtons method (https://en.wikipedia.org/wiki/Newton%27s_method), not secant method!
//Formula see: https://wiki.openoffice.org/wiki/Documentation/How_Tos/Calc:_Derivation_of_Financial_Formulas#PV.2C_FV.2C_PMT.2C_NPER.2C_RATE
f = Math.pow(1 + rate, nper);
y = pv * f + pmt * ((f - 1) / rate) * (1 + rate * type) + fv;
//first derivative:
//y1 = (pmt * nper * type * Math.pow(rate,2) * f - pmt * f - pmt * rate * f + pmt * nper * rate * f + pmt * rate + pmt + nper * pv * Math.pow(rate,2) * f) / (Math.pow(rate,2) * (rate+1));
y1 = (f * ((pmt * nper * type + nper * pv) * Math.pow(rate,2) + (pmt * nper - pmt) * rate - pmt) + pmt * rate + pmt) / (Math.pow(rate,3) + Math.pow(rate,2));
xN = rate - y/y1;
while ((Math.abs(rate - xN) > FINANCIAL_PRECISION) && (i < FINANCIAL_MAX_ITERATIONS)) {
rate = xN;
f = Math.pow(1 + rate, nper);
y = pv * f + pmt * ((f - 1) / rate) * (1 + rate * type) + fv;
//first derivative:
//y1 = (pmt * nper * type * Math.pow(rate,2) * f - pmt * f - pmt * rate * f + pmt * nper * rate * f + pmt * rate + pmt + nper * pv * Math.pow(rate,2) * f) / (Math.pow(rate,2) * (rate+1));
y1 = (f * ((pmt * nper * type + nper * pv) * Math.pow(rate,2) + (pmt * nper - pmt) * rate - pmt) + pmt * rate + pmt) / (Math.pow(rate,3) + Math.pow(rate,2));
xN = rate - y/y1;
++i;
System.out.println(rate+", "+xN+", "+y+", "+y1);
}
rate = xN;
return rate;
}
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(1);
Cell cell = row.createCell(1);
cell.setCellFormula("RATE(85.77534246575343, -1589.0, -18664.0, 5855586.0, 0, 0.06)");
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
CellType celltype = evaluator.evaluateFormulaCellEnum(cell);
double value = 0.0;
if (celltype == CellType.NUMERIC) {
value = cell.getNumericCellValue();
System.out.println(value);
}
workbook.setForceFormulaRecalculation(true);
value = calculateRateNewton(85.77534246575343, -1589.0, -18664.0, 5855586.0, 0, 0.1);
System.out.println(value);
workbook.write(new FileOutputStream("ExcelRATEFunction.xlsx"));
workbook.close();
}
}
I want need to know how detect center coordinates of quadraticCurve in HTML5 canvas. I want to draw arrow in this center point of curve.
There is my draw curve method:
function draw_curve(Ax, Ay, Bx, By, M, context) {
var dx = Bx - Ax,
dy = By - Ay,
dr = Math.sqrt(dx * dx + dy * dy);
// side is either 1 or -1 depending on which side you want the curve to be on.
// Find midpoint J
var Jx = Ax + (Bx - Ax) / 2
var Jy = Ay + (By - Ay) / 2
// We need a and b to find theta, and we need to know the sign of each to make sure that the orientation is correct.
var a = Bx - Ax
var asign = (a < 0 ? -1 : 1)
var b = By - Ay
var bsign = (b < 0 ? -1 : 1)
var theta = Math.atan(b / a)
// Find the point that's perpendicular to J on side
var costheta = asign * Math.cos(theta)
var sintheta = asign * Math.sin(theta)
// Find c and d
var c = M * sintheta
var d = M * costheta
// Use c and d to find Kx and Ky
var Kx = Jx - c
var Ky = Jy + d
// context.bezierCurveTo(Kx, Ky,Bx,By, Ax, Ax);
context.quadraticCurveTo(Kx, Ky, Bx, By);
// draw the ending arrowhead
var endRadians = Math.atan((dx) / (dy));
context.stroke();
var t = 0.5; // given example value
var xx = (1 - t) * (1 - t) * Ax + 2 * (1 - t) * t * Kx + t * t * Bx;
var yy = (1 - t) * (1 - t) * Ay + 2 * (1 - t) * t * Ky + t * t * By;
var k = {};
k.x = xx;
k.y = yy;
SOLVED BY THIS CODE, T is parameter which set position on the curve:
var t = 0.5; // given example value
var xx = (1 - t) * (1 - t) * Ax + 2 * (1 - t) * t * Kx + t * t * Bx;
var yy = (1 - t) * (1 - t) * Ay + 2 * (1 - t) * t * Ky + t * t * By;
var k = {};
k.x = xx;
k.y = yy;