how to find integrals from limit -infinity to +infinity in scilab - integration

How to find integrals from limits -infinity to +infinity in SCILAB ? ( Expression to be integrated are not directly integratable )

Change the variable of integration from x=(-inf,inf) to z=atan(x)
x=tan(z),
dx/dz = 1/(cos(z))^2
In the new variable z, the integration limits are from -%pi/2+eps to +%pi/2-eps, where eps is a very small positive number (else you will not be able to divide by the cos(z)) and
integral f(x) dx =
= integral f(x(z)) d(x(z))
= integral f(z) dx/dz dz
For example,
function y=Gaussian(x); y=exp(-x^2/2)/sqrt(2*%pi); endfunction;
intg(-10,10,Gaussian)
The same integration result is achieved with
function y=Gmodified(z); x=tan(z); y=Gaussian(x)/(cos(z))^2; endfunction;
intg(atan(-10),atan(10),Gmodified)
Interestingly, Scilab will take the above integral even for
intg(-%pi/2,%pi/2,Gmodified)
but this is only because Scilab evaluates 1/cos(%pi/2) as 1.633D+16 rather than infinity.

Related

Octave, finding the maximum of a numeric function

I am trying to compute the maximum value of the solution of a system with two ODEs using Octave. I have firstly solved the system itself:
function xdot = f (x,t)
a1=0.00875;
a2=0.075;
b1=7.5;
b2=2.5;
d1=0.0001;
d2=0.0001;
g=4*10^(-8);
K1=5000;
K2=2500;
n=2;
m=2;
xdot = zeros(2,1);
xdot(1) = a1+b1*x(1)^n/(K1^n+x(1)^n)-g*x(1)*x(2)-d1*x(1);
xdot(2) = a2+b2*x(1)^m/(K2^m+x(1)^m)-d2*x(2);
endfunction
t = linspace(0, 5000, 200)';
x0 = [1000; 1000];
x = lsode ("f", x0, t);
set term dumb;
plot(t,x);
But now I do not know how to compute the maximum value of the two functions (numerical ones) obtained as solutions of the system. I have searched in the Internet but I haven't found what I want... I only have found the function fminbnd for the minimum of a function on an interval...
Is it possible to compute the maximum value of a numeric function with Octave?
Generally, if you know how to find the minimum of a function, you also know how to find its maximum: just look for the minimum of -f.
However, fminbnd is designed for functions that can be evaluated at any given point. What you have is just a vector of 200 points. In principle, you could use interpolation to get a function and then maximize that. But this is not really needed, because all the information you have is in that matrix x anyway, so it makes sense to just take the maximum value there. Like this:
[x1m, i1] = max(x(:,1));
[x2m, i2] = max(x(:,2));
disp(sprintf('Maximum of x1 is %f attained at t = %f', x1m, t(i1)));
disp(sprintf('Maximum of x1 is %f attained at t = %f', x2m, t(i2)));

How to generate random numbers from log-normal distribution with a given mean and SD in SAS?

Wenping (Wendy) Zhang points out
that the SAS RAND function "basically gives "standard" distribution".
The author describes an interesting SAS %rndnmb macro to generate data from “non-standard” distributions. Unfortunately the code in unavailable. So, I dared to do it by myself.
If I understand correctly the Wikipedia says that y is from the log-normal distribution if
y = exp^(mu + sigma * Z).
The following formulas connect the mean and variance of the non-logarithmized sample values:
mu = ln((mean^2)/(sqrt(variance + mean^2))
and
sigma = sqrt(ln(1 + (variance)/(mean^2))).
If that correct, my y will be drawn from log-normal distribution when
Z is from standard normal distribution Z with mu' = 0, sigma' = 1.
Finally, is it correct that y is from lognormal distribution with mean and variance if
y = exp^(ln((mean^2)/(sqrt(variance + mean^2)) + sqrt(ln(1 + (variance)/(mean^2))) * Z)
?
My SAS code is:
/*I use StdDev^2 notation instead of variance here. */
DATA nonStLogNorm;
nonStLN = exp(1)**(log((mean**2)/(sqrt(StdDev^2 + mean**2)) +
sqrt(log(1 + (StdDev^2)/(mean**2))) * rand('UNIFORM'));
RUN;
References:
RAND function by Rick Wicklin:
http://blogs.sas.com/content/iml/2013/07/10/stop-using-ranuni/
http://blogs.sas.com/content/iml/2011/08/24/how-to-generate-random-numbers-in-sas/
What you need is the inverse cumulative distribution function. This is the function that is the inverse of the normalized integral of the distribution over the entire domain. So at 0% is your most negative possible value and 100% is your most positive. Practically though you would calmp to something like 0.01% and 99.99% or something like that as otherwise you'll end up at infinite for a lot of distributions.
Then from there you only need to random a number in a range (0,1) and plug that into the function. Remember to clamp it!
double CDF = 0.5 + 0.5*erf((ln(x) - center)/(sqrt(2)*sigma))
so
double x = exp(inverf((CDF - 0.5)*2.0)*sqrt(2)*sigma + center);
should give you the requested distribution. inverf is the inverse of the erf function. It is a common function but not in math.h typically.
Did a SIMD based random number generator that needed to do distributions. This worked fine, the above will work assuming I didn't flub up something while typing.
As requested how to clamp:
//This is how I do it with my Random class where the first argument
//is the min value and the second is the max
double CDF = Random::Range(0.0001,0.9999); //Depends on what you are using to random
//How you get there from Random Ints
unsigned int RandomNumber = rand();
//Conver number to range [0,1]
double CDF = (double)RandomNumber/(double)RAND_MAX;
//now clamp it to a min, max of your choosing
CDF = CDF*(max - min) + min;
If you want Z to be drawn from the standard normal distribution, shouldn't you obtain it by calling RAND('NORMAL') rather than RAND('UNIFORM')?

Defining a Differential Equation in Octave

I am attempting to use Octave to solve for a differential equation using Euler's method.
The Euler method was given to me (and is correct), which works for the given Initial Value Problem,
y*y'' + (y')^2 + 1 = 0; y(1) = 1;
That initial value problem is defined in the following Octave function:
function [YDOT] = f(t, Y)
YDOT(1) = Y(2);
YDOT(2) = -(1 + Y(2)^2)/Y(1);
The question I have is about this function definition. Why is YDOT(1) != 1? What is Y(2)?
I have not found any documentation on the definition of a function using function [YDOT] instead of simply function YDOT, and I would appreciate any clarification on what the Octave code is doing.
First things first: You have a (non linear) differential equation of order two which will require you to have two initial conditions. Thus the given information from above is not enough.
The following is defined for further explanations: A==B means A is identical to B; A=>B means B follows from A.
It seems you are mixing a few things. The guy who gave you the files rewrote the equation in the following way:
y*y'' + (y')^2 + 1 = 0; y(1) = 1; | (I) y := y1 & (II) y' := y2
(I) & (II)=>(III): y' = y2 = y1' | y2==Y(2) & y1'==YDOT(1)
Ocatve is "matrix/vector oriented" so we are writing everything in vectors or matrices. Rather writing y1=alpha and y2=beta we are writing y=[alpha; beta] where y(1)==y1=alpha and y(2)==y2=beta. You will soon realize the tremendous advantage of using especially this mathematical formalization for ALL of your problems.
(III) & f(t,Y)=>(IV): y2' == YDOT(2) = y'' = (-1 -(y')^2) / y
Now recall what is y' and y from the definitions in (I) and (II)!
y' = y2 == Y(2) & y = y1 == Y(1)
So we can rewrite equation (IV)
(IV): y2' == YDOT(2) = (-1 -(y')^2) / y == -(1 + Y(2)^2)/Y(1)
So from equation (III) and (IV) we can derive what you already know:
YDOT(1) = Y(2)
YDOT(2) = -(1 + Y(2)^2)/Y(1)
These equations are passed to the solver. Differential equations of all types are solved numerically by retrieving the "next" value in a near neighborhood to some "previously known" value. (The step size inside this neighborhood is one of the key questions when writing solvers!) So your solver uses your initial condition Y(1)==y(1)=1 to make the next step and calculate the "next" value. So right at the start YDOT(1)=Y(2)==y(2) but you didn't tell us this value! But from then on YDOT(1) is varied by the solver in dependency to the function shape to solve your problem and give you ONE unique y(t) solution.
It seems you are using Octave for the first time so let's make a last comment on function [YDOT] = f(t, Y). In general a function is defined in this way:
function[retVal1, retVal2, ...] = myArbitraryName(arg1, arg2, ...)
Where retVal is the return value or output and arg is the argument or input.

Creating a function from a 2D array in MATLAB (For use in ode45)

I am a first time MATLAB user. I have a 2d array of t vs f in MATLAB. This 2d array correponds to a function, say f(t). I am using ode45 to solve a set of differential equations and f(t) is one of the coefficients i.e. I have a set of equations of the form x'(t)=f(t)x(t) or variations thereof. How do I proceed?
I need a way to convert my array of t vs f into a function that can be used in the ode45 method. Presumably, the conversion will do some linear interpolation and give me the equation of the best fit curve.
Or if there is another approach, I'm all ears!
Thank you!
This is a simple example with passing function as a parameter to right hand side of the ODE. Create files in the same directory and run main
main.m
t = 0:0.2:10; f = sin(t);
fun = #(xc) interp1(t, f, xc);
x0=0.5
% solve diff(x, t)=sin(t)
% pass function as parameter
[tsol, xsol] = ode45(#(t, x) diff_rhs(t, x, fun),[0.0 8.0], 0.5);
% we solve equation dx/dt = sin(x), x(0)=x0
% exact solution is x(t) = - cos(t) + x(0) + 1
plot(tsol, xsol, 'x');
hold on
plot(tsol, -cos(tsol) + x0 + 1, '-');
legend('numerical', 'exact');
diff_rhs.m
function dx = diff_rhs(t, x, fun)
dx = fun(t);
end
References in the documentation: interp1 and anonymous Functions.

summing functions handles in matlab

Hi
I am trying to sum two function handles, but it doesn't work.
for example:
y1=#(x)(x*x);
y2=#(x)(x*x+3*x);
y3=y1+y2
The error I receive is "??? Undefined function or method 'plus' for input arguments of type 'function_handle'."
This is just a small example, in reality I actually need to iteratively sum about 500 functions that are dependent on each other.
EDIT
The solution by Clement J. indeed works but I couldn't manage to generalize this into a loop and ran into a problem. I have the function s=#(x,y,z)((1-exp(-x*y)-z)*exp(-x*y)); And I have a vector v that contains 536 data points and another vector w that also contains 536 data points. My goal is to sum up s(v(i),y,w(i)) for i=1...536 Thus getting one function in the variable y which is the sum of 536 functions. The syntax I tried in order to do this is:
sum=#(y)(s(v(1),y,z2(1)));
for i=2:536
sum=#(y)(sum+s(v(i),y,z2(i)))
end
The solution proposed by Fyodor Soikin works.
>> y3=#(x)(y1(x) + y2(x))
y3 =
#(x) (y1 (x) + y2 (x))
If you want to do it on multiple functions you can use intermediate variables :
>> f1 = y1;
>> f2 = y2;
>> y3=#(x)(f1(x) + f2(x))
EDIT after the comment:
I'm not sure to understand the problem. Can you define your vectors v and w like that outside the function :
v = [5 4]; % your 536 data
w = [4 5];
y = 8;
s=#(y)((1-exp(-v*y)-w).*exp(-v*y))
s_sum = sum(s(y))
Note the dot in the multiplication to do it element-wise.
I think the most succinct solution is given in the comment by Mikhail. I'll flesh it out in more detail...
First, you will want to modify your anonymous function s so that it can operate on vector inputs of the same size as well as scalar inputs (as suggested by Clement J.) by using element-wise arithmetic operators as follows:
s = #(x,y,z) (1-exp(-x.*y)-z).*exp(-x.*y); %# Note the periods
Then, assuming that you have vectors v and w defined in the given workspace, you can create a new function sy that, for a given scalar value of y, will sum across s evaluated at each set of values in v and w:
sy = #(y) sum(s(v,y,w));
If you want to evaluate this function using an array of values for y, you can add a call to the function ARRAYFUN like so:
sy = #(y) arrayfun(#(yi) sum(s(v,yi,w)),y);
Note that the values for v and w that will be used in the function sy will be fixed to what they were when the function was created. In other words, changing v and w in the workspace will not change the values used by sy. Note also that I didn't name the new anonymous function sum, since there is already a built-in function with that name.