Serving the Quantitative Finance Community

 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

February 26th, 2021, 8:47 am

Please read my post in off-topic requesting American tax payers to cut US defense spending and the reasons I have cited. 
https://forum.wilmott.com/viewtopic.php?f=15&t=94796&start=1200#p864520
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 1st, 2021, 7:56 pm

Friends, I am sorry for the delay in completing the new program I have been talking about in previous posts. I am trying to fix errors in my program. For example it seems to work well when I start constructing the grid cells boundary away from the origin towards positive territory when probability defect in the subdivisions is negative but seems to be off when the probability defect is positive. I am still thinking of reasons and want to try to fix it in next two or three days.
I had proclaimed victory in one of my posts more than a week ago but later I found there were some more problems. I really hope that I will get my program to work in next few days.
I want to request good friends to please protest to mind control agencies and stop them from forcing me back on injections. Please read my detailed post in off-topic. https://forum.wilmott.com/viewtopic.php?f=15&t=94796&p=864588#p864588
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 2nd, 2021, 9:47 am

Friends, here is the new update about progress on the new program. The program works perfectly well till three standard deviations of underlying normal. I calculate CDF at the trial boundary, calculate probability mass defect and find the true boundary using a quartic equation as I earlier described. I then again check the CDF at true calculated boundary and calculate new probability mass defect and it seems that quartic equation works very well in solution of the problem(as the new probability mass defect in the subdivision is extremely small)  but the solution is still off from 3 SD to 5 SD on both directions(off by extremely little on 3SD but increasingly off as we move to 5SD). Since quartic equation solution seems to work very well, it seems that my CDF formulas(and consequently its derivatives formulas) that I am using are still slightly off between 3SD to 5SD. I will work on improving the CDF formulas (and checking for possible errors). Apparently it seems that CDF formulas need a higher order expansion as we move from 3SD to 5SD but things would be clear when I check them more carefully in the evening today. 
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 4th, 2021, 2:22 am

Friends, I have tried to find the reason why my program does not work perfectly between 3sd to 5sd but the problem still persists. For one step it evolves the density with extreme precision as there is only miniscule probability mass between 3sd to 5sd of underlying normal. For multistep evolution, either we have to use extrapolation of sde variable against normal variable or use some other method between 3sd to 5sd. I will post my program for friends in another day or two after cleaning up the code and adding proper comments. It is a good program and i hope friends will like it.
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 5th, 2021, 4:34 am

Dear friends, In this post, I will try to explain with a bit more clarity how to calculate the transition CDF.PDF, and their derivatives between a whole grid cell at time t to an arbitrary point at time t+1. I will use the previous notation but with some slight changes, write and explain equations and later(in the same post) post the function code to calculate those CDF, PDF and its derivatives. I will also post some(simple) code that I used to compare results of some analytic integrals in above formulas with numerical integration. Today, I will only post the above function and related code and post the whole working program with explanatory comments tomorrow. And yes, I will post the simplified version of solution to quartic equation today(that will be used by the main code that I will post tomorrow).
I am copying my old post for reference but will try to explain things again.
Amin:
Post in progress.
I tried a bit to see if I could further improve on the formula for probability mass transfer CDF I wrote a few posts ago. I am copying equation(E) from the relevant earlier post. 
We write the above results of Equation(D) and substitute them in equation (C) and take constants out of the integrals to write the equation(E) as 
[$]\int_{B_{m1}}^{B_{m2}} p_m(B) P_{m,n}(B) dB[$]
[$]=\Delta P_m P_{m0,n}[$]
[$]+ ( p_{m0} p_{m0,n})  \int_{B_{m1}}^{B_{m2}}  (B - B_{m0}) dB[$]
[$]+ (2 \frac{dp_{m0}}{dB} p_{m0,n}+  p_{m0} \frac{dp_{m0,n}}{dB}) \int_{B_{m1}}^{B_{m2}}  \frac{ {(B - B_{m0})}^2}{2} dB[$]
[$]+(3 \frac{d^2p_{m0}}{d{B}^2} p_{m0,n}+3 \frac{dp_{m0}}{dB} \frac{dp_{m0,n}}{dB}+  p_{m0} \frac{d^2p_{m0,n}}{dB^3})  \int_{B_{m1}}^{B_{m2}}   \frac{{(B - B_{m0})}^3}{6}  dB[$]  Equation(E)

We have earlier simplified the equation by collecting some terms and recognizing their series and finding the term that describes the series. We want to try doing that with some other terms as well but it is a bit more difficult now.
Let us put separate some more terms and try to simplify them as

[$] ( p_{m0} p_{m0,n})  \int_{B_{m1}}^{B_{m2}}  (B - B_{m0}) dB[$]
[$]+ (p_{m0} \frac{dp_{m0,n}}{dB}) \int_{B_{m1}}^{B_{m2}}  \frac{ {(B - B_{m0})}^2}{2} dB[$]
[$]+(p_{m0} \frac{d^2p_{m0,n}}{dB^3})  \int_{B_{m1}}^{B_{m2}}   \frac{{(B - B_{m0})}^3}{6}  dB[$]  equation(a)

The above three terms could  be recognized as series for integral of CDF if we could add first order Taylor term that it is missing. So we could write as
[$]\int_{B_{m1}}^{B_{m2}} p_{m0} P_{m,n}(B) dB[$]
[$] -  \int_{B_{m1}}^{B_{m2}} ( p_{m0} P_{m0,n})  dB[$]
[$] =  \int_{B_{m1}}^{B_{m2}}  ( p_{m0} p_{m0,n})(B - B_{m0}) dB[$]
[$]+  \int_{B_{m1}}^{B_{m2}} (p_{m0} \frac{dp_{m0,n}}{dB}) \frac{ {(B - B_{m0})}^2}{2} dB[$]
[$]+ \int_{B_{m1}}^{B_{m2}} (p_{m0} \frac{d^2p_{m0,n}}{dB^3})   \frac{{(B - B_{m0})}^3}{6}  dB[$] equation(b)

So we can basically replace the series continuation of the following terms  
[$] ( p_{m0} p_{m0,n})  \int_{B_{m1}}^{B_{m2}}  (B - B_{m0}) dB[$]
[$]+ (p_{m0} \frac{dp_{m0,n}}{dB}) \int_{B_{m1}}^{B_{m2}}  \frac{ {(B - B_{m0})}^2}{2} dB[$]
[$]+(p_{m0} \frac{d^2p_{m0,n}}{dB^3})  \int_{B_{m1}}^{B_{m2}}   \frac{{(B - B_{m0})}^3}{6}  dB[$] Equation(a)

with the following two terms

[$] p_{m0} \int_{B_{m1}}^{B_{m2}} P_{m,n}(B) dB[$]
[$] - ( p_{m0} P_{m0,n}) \int_{B_{m1}}^{B_{m2}}   dB[$] Equation(c)

The first analytic integral might be hard to solve analytically but we can try to integrate it by parts as 
[$]  \int_{B_{m1}}^{B_{m2}} P_{m,n} dB[$]
[$]=B_{m2} P_{m2,n} - B_{m1} P_{m1,n}  - \int_{B_{m1}}^{B_{m2}}  B p_{m,n}(B) dB[$]  Equation(d)

Substituting Equation(d) in Equation(c), we get
[$] p_{m0} \int_{B_{m1}}^{B_{m2}} P_{m,n}(B) dB[$]
[$] - ( p_{m0} P_{m0,n}) \int_{B_{m1}}^{B_{m2}}   dB[$]
[$]=p_{m0} B_{m2} P_{m2,n} -p_{m0} B_{m1} P_{m1,n} [$]
[$]- p_{m0} \int_{B_{m1}}^{B_{m2}}B p_{m,n}(B) dB[$]
[$] - ( p_{m0} P_{m0,n}) \int_{B_{m1}}^{B_{m2}}   dB[$] Equation(e)

Now we can substitute equation(e) in the original equa.tion(E) and write as
[$]\int_{B_{m1}}^{B_{m2}} p_m(B) P_{m,n}(B) dB[$]
[$]=\Delta P_m P_{m0,n}[$]
[$]+p_{m0} B_{m2} P_{m2,n} -p_{m0} B_{m1} P_{m1,n} [$]
[$]- p_{m0} \int_{B_{m1}}^{B_{m2}}B p_{m,n}(B) dB[$]
[$] - ( p_{m0} P_{m0,n}) \int_{B_{m1}}^{B_{m2}}   dB[$]
[$]+ (2 \frac{dp_{m0}}{dB} p_{m0,n}) \int_{B_{m1}}^{B_{m2}}  \frac{ {(B - B_{m0})}^2}{2} dB[$]
[$]+(3 \frac{d^2p_{m0}}{d{B}^2} p_{m0,n}+3 \frac{dp_{m0}}{dB} \frac{dp_{m0,n}}{dB})  \int_{B_{m1}}^{B_{m2}}   \frac{{(B - B_{m0})}^3}{6}  dB[$] 
[$] + higher order terms [$] 
EDIT: In some of the integrals below I have used dB and mostly I have used [$]dB_m[$] but both are the same. I forgot the subscript m in some integrals. But I hope that friends would still perfectly understand as I have given reasonable orientation explanation for most of the integrals.
 
In this post, I want to write how to calculate exact Gaussian transition CDF, Gaussian transition probability and derivatives of Gaussian transition probability from mth Bessel grid cell  [$]B_m[$] at time t, to any point on the new grid at time t+1. 

Let us fix the notation first. We have a Bessel grid and we indicate points in an arbitrary cell by [$]B_m[$](this is notation, we use when we integrate over the originating cell etc) and the center of this cell is given by [$]B_{m0}[$]. 
This center [$]B_{m0}[$] will correspond to point [$]Z_m[$] on Z-grid and in general both boundaries of the cell(that will correspond to [$]Z_m+\Delta Z_m/2[$] and [$]Z_m-\Delta Z_m/2[$]) will not be equidistant from this center of the cell [$]B_{m0}[$]. We will represent the left boundary of cell [$]B_m[$] corresponding to [$]Z_m-\Delta Z_m/2[$] as  [$]B_{m1}[$] and right boundary corresponding to  [$]Z_m+\Delta Z_m/2[$]  as [$]B_{m2}[$]
Please note that gaussian [$]Z_m[$] that underlies the originating bessel grid is different from the transition gaussian between any point on the originating grid cell [$]B_m[$] to some target point [$]B_n[$] on grid at time t+1 which is indicated with [$]Z_t[$]. By definition [$]Z_t=B_n(t+1)-B_m(t)[$]. Since in the following analyticss, we have to calculate derivatives of gaussian [$]Z_t[$] with respect to both [$]B_n[$] and [$]B_m[$], we denote the derivatives with respect to [$]B_n[$] with a simplified notation using apostrophe on the original variable and derivatives with respect to [$]B_m[$] with a fraction notation. Please note that
[$]\frac{\partial B_n}{\partial Z_t}=1[$] and
[$]\frac{\partial B_m}{\partial Z_t}=-1[$]

The transition probability between arbitrary point on mth cell [$]B_{m}[$] to arbitary point [$]B_n[$] on next grid is denoted as [$] p_{m,n}=N(B_n-B_{m},0,\sigma_m)[$].Its CDF is defined by uppercase of PDF as [$] P_{m,n}=\int_{-\infty}^{(B_n-B_{m})} N(B_n-B_{m},0,\sigma_m) dN [$] 
When we expand around center of mth grid cell [$]B_{m0}[$], the above quantities change notation and the transition probability between center of mth cell [$]B_{m0}[$] to arbitary point [$]B_n[$] on next grid is denoted as [$] p_{m0,n}=N(B_n-B_{m0},0,\sigma_m)[$].Its CDF is defined by uppercase of PDF as [$] P_{m0,n}=\int_{-\infty}^{(B_n-B_{m0})} N(B_n-B_{m0},0,\sigma_m) dN [$]
When we calculate kth derivative of CDF or its other derivatives (with respect to target [$]B_n[$]) further with respect to originating cell [$]B_m[$], we use the simple formula [$]\frac{\partial^k P_{m,n}}{\partial {B_m}^k}[$][$]=\frac{\partial^k P_{m,n}}{\partial {Z_t}^k} {(\frac{\partial Z_t}{\partial B_m})}^k[$][$]={P_{m,n}}^{(k)}(Zt) * {(-1)}^{k}[$] since  [$]\frac{\partial Z_t}{\partial B_m}=-1[$]

Now we come to derivatives of PDF in the originating cell [$]B_m[$] with underlying unit gaussian [$]Z_m[$]. Please note that this gaussian [$]Z_m[$] underlying originating cell [$]B_m[$] is different from transition gaussian [$]Z_t[$] between originating cell [$]B_m(t)[$] and target cell [$]B_n(t+1)[$]. In the following paragraph, we are only concerned with probability distribution and its derivatives in the originating cell [$]B_m[$]. In general, This probability distribution in originating cell is not a gaussian probability but this PDF and its derivatives in mth cell are related to  underlying gaussian probability [$]Z_m[$] by change of variable formula for distributions.
We define the probability density function at center of mth cell in Bessel variable [$]B_m[$] as lowercase [$]p_{m0}=p(Z_m) \frac{dZ}{dB_m}[$] while uppercase will denote its CDF given as [$]P_{m0}=P(Z_m)[$]
The probability mass in mth cell which is the difference of CDF at boundaries is denoted as [$]\Delta P_{m}[$] 
The derivatives of  probability density function at center of mth cell in Bessel variable [$]B_m[$] are given as[$]\frac{dp_{m0}}{dB}=\frac{dp(Z_m)}{dZ} {(\frac{dZ}{dB_m})}^2+p(Z_m) \frac{d^2Z}{d{B_m}^2} [$]
We can similarly calculate higher derivatives [$]\frac{d^2p_{m0}}{d{B}^2}(B_{m0})[$] and [$]\frac{d^3p_{m0}}{d{B}^3}[$] by further differentiating the above function. (I calculated these derivatives in the main body of the program since they have to be calculated just once for every transition to target points and calculating them in the function that calculates CDF and its derivatives from originating cell to target points was not appropriate. They are simply input to the function that calculates CDF and its derivatives to target points at t+1 from a particular cell at time t.)
Again please note the difference that  [$]P_{m0}[$] and [$]p_{m0}[$] are CDF and its PDF in the originating cell(calculated at its center) while [$]P_{m0,n}[$] and [$]p_{m0,n}[$] are transition CDF and PDF respectively between center of originating cell and the target point [$]B_n[$] on next time grid.
We want to calculate the transition CDF, transition probability, and its derivatives from a cell m at time t, to an arbitrary point n on the grid at time t+1.  
We first calculate the CDF from entire mth cell to nth point on grid at time t+1 and write it as an integral as
[$]\int_{B_{m1}}^{B_{m2}} p_m(B_m) P_{m,n}(B_m) dB_m[$] Equation(A)
Here [$]p_m(B_m)[$] indicates the probability density function at arbitrary point [$]B_m[$] within the mth subdivision(not necessarily at center).
Here [$]P_{m,n}(B_m)[$] indicates the CDF of transition probability from an arbitrary point [$]B_m[$] within the mth subdivision(not necessarily from its center) to arbitrary point [$]B_n[$] on next (time level) grid such that [$]Z_t=B_n - B_m[$].
Our strategy to solve the above integral is to take derivatives of integrand at center of the grid cell [$]B_{m0}[$] and expand it as Taylor series and then solve it. Our expansion is basically constant values calculated at center of the mth subdivision(which are handily available) multiplied by an integral of the powers of difference of distance of two boundaries from the center. I have already indicated previously how to calculate these derivatives at center to any higher order.

So we have (in the following equation B indicates [$]B_m[$]. I have omitted m in subscript in the expansion after the first line.) 
[$]\int_{B_{m1}}^{B_{m2}} p_m(B_m) P_{m,n} dB_m[$]
[$]=\int_{B_{m1}}^{B_{m2}} p_{m0} P_{m0,n} dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  (\frac{dp_{m0}}{dB} P_{m0,n}+ p_{m0} \frac{dP_{m0,n}}{dB})  (B - B_{m0}) dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  (\frac{d^2p_{m0}}{d{B}^2} P_{m0,n}+2 \frac{dp_{m0}}{dB} \frac{dP_{m0,n}}{dB}+  p_{m0} \frac{d^2P_{m0,n}}{dB^2})  \frac{{(B - B_{m0})}^2}{2}  dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  (\frac{d^3p_{m0}}{d{B}^3} P_{m0,n}+3 \frac{d^2p_{m0}}{d{B}^2} \frac{dP_{m0,n}}{dB}+3 \frac{dp_{m0}}{dB} \frac{d^2P_{m0,n}}{dB^2}+  p_{m0} \frac{d^3P_{m0,n}}{dB^3})  \frac{{(B - B_{m0})}^3}{6}   dB[$]  Equation(B)
[$]+ higher order terms in Taylor series[$]
Please note again that in the above equation odd derivatives of transition CDF with respect to [$]B_m[$] or B (abbreviated notation) will take a negative sign with respect to regular(plain) transition CDF and its derivatives(with respect to [$]Z_t[$] as [$]\frac{dB_m}{dZ_t}=-1[$].
We rearrange the above equation in further three groups of terms. Then We find analytic approximation to two of those three groups and add simply add the third group as such.
[$]\int_{B_{m1}}^{B_{m2}} p_m(B_m) P_{m,n}(B_m) dB_m[$]
[$]=G1 + G2 + G3[$]
where

[$]G1=\int_{B_{m1}}^{B_{m2}} p_{m0} P_{m0,n} dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  (\frac{dp_{m0}}{dB} P_{m0,n})  (B - B_{m0}) dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  (\frac{d^2p_{m0}}{d{B}^2} P_{m0,n})  \frac{{(B - B_{m0})}^2}{2}  dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  (\frac{d^3p_{m0}}{d{B}^3} P_{m0,n})  \frac{{(B - B_{m0})}^3}{6}   dB[$]
and
[$]G2=\int_{B_{m1}}^{B_{m2}}  ( p_{m0} \frac{dP_{m0,n}}{dB})  (B - B_{m0}) dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  ( p_{m0} \frac{d^2P_{m0,n}}{dB^2})  \frac{{(B - B_{m0})}^2}{2}  dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  (p_{m0} \frac{d^3P_{m0,n}}{dB^3})  \frac{{(B - B_{m0})}^3}{6}   dB[$]

[$]G3=\int_{B_{m1}}^{B_{m2}}  (2 \frac{dp_{m0}}{dB} \frac{dP_{m0,n}}{dB})  \frac{{(B - B_{m0})}^2}{2}  dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  (3 \frac{d^2p_{m0}}{d{B}^2} \frac{dP_{m0,n}}{dB}+3 \frac{dp_{m0}}{dB} \frac{d^2P_{m0,n}}{dB^2})  \frac{{(B - B_{m0})}^3}{6}   dB[$] Equation(C)

We notice that after taking [$]P_{m0,n}[$] common out of terms in G!, the terms in G1(and their taylor series continuation) are integral of a simple Taylor expansion of probability density function in the originating mth Grid at time t and hence represent the integral of probability mass in mth subdivision. Hence we can write this group G1 as  
[$]G1= P_{m0,n} \int_{B_{m1}}^{B_{m2}} p_{m}(B_m) dB_m= P_{m0,n} \Delta P_m[$]

where [$]\Delta P_m[$] indicates total (integral of) probability mass in the mth subdivision.  

Now we take the second group of terms.
[$]G2=\int_{B_{m1}}^{B_{m2}}  ( p_{m0} \frac{dP_{m0,n}}{dB})  (B - B_{m0}) dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  ( p_{m0} \frac{d^2P_{m0,n}}{dB^2})  \frac{{(B - B_{m0})}^2}{2}  dB[$]
[$]+\int_{B_{m1}}^{B_{m2}}  (p_{m0} \frac{d^3P_{m0,n}}{dB^3})  \frac{{(B - B_{m0})}^3}{6}   dB[$]
We notice that if we take [$] p_{m0}[$] common, this group of terms (and their taylor series continuation) would equal the (non-probability weighted) integral of transition CDF over the mth subdivision but in order to do that we will have to add one first term in the series that would equal [$]T2= \int_{B_{m1}}^{B_{m2}}   p_{m0} P_{m0,n} dB[$]. Only if we could add T2 to this G2 group of terms, it would be equal to (non-probability weighted) integral of transition CDF over mth subdivision. So we can write 

[$]G2= p_{m0} \int_{B_{m1}}^{B_{m2}} P_{m,n}(B_m) dB_m-\int_{B_{m1}}^{B_{m2}}   p_{m0} P_{m0,n} dB [$]
The term T2 we added over G2 is very simple but we would still have to see how to analytically solve (non-probability weighted) integral of CDF over mth subdivision given as [$]\int_{B_{m1}}^{B_{m2}} P_{m,n}(B_m) dB_m[$]. In order to solve this integral by parts as
[$]\int_{B_{m1}}^{B_{m2}} P_{m,n}(B_m) dB_m=\int_{B_{m1}}^{B_{m2}} d[B_m P_{m,n}(B_m)] - \int_{B_{m1}}^{B_{m2}} B_m \frac{d P_{m,n}}{dB_m} dB_m  [$]
[$]=B_{m2} P_{m2,n} - B_{m1} P_{m1,n} - \int_{B_{m1}}^{B_{m2}} B_m \frac{d P_{m,n}}{dB_m} dB_m  [$]
In order to solve the second term in last line, we write as
[$]\int_{B_{m1}}^{B_{m2}} B_m \frac{d P_{m,n}}{dB_m} dB_m  [$]
We notice that [$]B_m=B_n-Z_t[$]  , [$]\frac{d P_{m,n}}{dB_m}= -p_{m,n}(Z_t)[$] and [$]dB_m=- dZ_t[$], [$]Z_{Bm1}=B_n - B_{m1}[$] and [$]Z_{Bm2}=B_n - B_{m2}[$]
so the integral in question becomes  
[$]\int_{B_{m1}}^{B_{m2}} B_m \frac{d P_{m,n}}{dB_m} dB_m =\int_{Z_{Bm1}}^{Z_{Bm2}} ( B_n-Z_t) p_{m,n}(Z_t) dZ_t[$]
dropping the subscript t in the notation of transition gaussian, we write the above equation as
[$]=\int_{Z_{Bm1}}^{Z_{Bm2}} ( B_n-Z) p_{m,n}(Z) dZ= B_n \int_{Z_{Bm1}}^{Z_{Bm2}} p(Z) dZ - \int_{Z_{Bm1}}^{Z_{Bm2}}  Z p(Z) dZ[$]
Both of the above integrals can be solved analytically. I checked the whole of this by parts analytic solution by comparing it with numerical integration of the(non-probability weighted)  CDF over different subdivisions and found it to be the right formula. In the end today, I will also give some (informal) programs I used to compare this by parts integral with numerical integration.
With the above calculations, the terms in group G2 equal to the expression as
[$]G2= p_{m0} \int_{B_{m1}}^{B_{m2}} P_{m,n}(B_m) dB_m-\int_{B_{m1}}^{B_{m2}}   p_{m0} P_{m0,n} dB [$]
[$]= p_{m0} (B_{m2} P_{m2,n} - B_{m1} P_{m1,n} ) - p_{m0} B_n \int_{Z_{Bm1}}^{Z_{Bm2}} p(Z) dZ + p_{m0} \int_{Z_{Bm1}}^{Z_{Bm2}}  Z p(Z) dZ[$]
[$]- p_{m0} P_{m0,n} \int_{B_{m1}}^{B_{m2}}  dB [$]
Please note that gaussian Z in above is not a unit gaussian, and it takes variance associated with the transition probability.
We add the terms in group G3 individually without any special analytical treatment.

I am pasting the code in next post.
Last edited by Amin on March 5th, 2021, 11:36 am, edited 1 time in total.
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 5th, 2021, 10:45 am

Below is the function that calculates transition CDF, transition PDF and its derivatives at an arbitrary point Bn at time t+1 from a whole grid cell Bm at time t when the transition is dictated by a gaussian probability distribution function with standard deviation sigma0 on mth cell Bm. we consider the effect(CDF, PDF and derivatives) from an entire grid cell on the target cell Bn on next time level. The probability distribution function of the originating grid is not a gaussian and represents the Bessel distribution associated with an SDE. But the same logic can possibly work if you have two arbitrary distributions and you can calculate derivatives of transition probability distribution and those of the probability distribution of originating grid cell.
I will post the full working programs tomorrow as I mentioned in previous post.
function [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(Bn,sigma0,Bm0,Bm1,Bm2,dPm,pm0,dpm0,d2pm0,d3pm0,d4pm0,d5pm0)

%This function calculates transition CDF Pmn, PDF pmn, first derivative of Pdf dpmn,
%second derivative of PDF d2pmn, and third derivative of PDF d3pmn at an
%arbitrary point Bn on next time level grid. All these CDF, PDF and their
%derivatives are calculated from an entire subdivision Bm at time t grid.
%Bm1 and Bm2 are boundaries of grid cell Bm and Bm0 is center of grid cell
%Bm. 
% sigma0 is the volatility associated with transition gaussian originating
% from the center of grid Bm given as Bm0.
%dPm is the integrate probability mass in mth originating subdivision.
%pm0 is the value of probability distribution at the center of mth cell at 
%Bm0.
%dpm0 is the value of first derivative of probability distribution at the
%center of mth subdivision at Bm0;
%and so on for d2pm0(second derivative of pdf at Bm0), d3pm0, d4pm0, d5pm0.
%pdf and all its derivatives at center of mth subdivsion Bm0 are input to
%the function.
%This program is not written with regard to efficiency at all and I will
%optimize the final version for efficiency.

Bt=Bn-Bm0;
Zt=(Bn-Bm0)/sigma0;
Zt2=Zt^2;
Zt3=Zt^3;
Zt4=Zt^4;
Zt5=Zt^5;
Zt6=Zt^6;
Zt7=Zt^7;
Zt8=Zt^8;
cc1=sigma0;
cc2=sigma0^2;
cc3=sigma0^3;
cc4=sigma0^4;
cc5=sigma0^5;
cc6=sigma0^6;
cc7=sigma0^7;
cc8=sigma0^8;

Pm0n=normcdf(Bt,0,cc1);
dPm0ndZt=normpdf(Bt,0,cc1);
pm0n=normpdf(Bt,0,cc1);
d2Pm0ndZt2=-pm0n*(Zt)./cc1;
d3Pm0ndZt3=pm0n*(Zt2-1)./cc2;
d4Pm0ndZt4=-pm0n*(Zt3-3*Zt)./cc3;
d5Pm0ndZt5=pm0n*(Zt4-6*Zt2+3)./cc4;
d6Pm0ndZt6=-pm0n*(Zt5-10*Zt3+15*Zt)./cc5;
d7Pm0ndZt7=pm0n*(Zt6-15*Zt4+45*Zt2-15)./cc6;
d8Pm0ndZt8=-pm0n*(Zt7-21*Zt5+105*Zt3-105*Zt)/cc7;                      
d9Pm0ndZt9=pm0n*(Zt8-28*Zt6+210*Zt4-420*Zt2+105)./cc8;

%dBmdZt=-1;
dZtdBm=-1;

Zm1=Bn-(Bm1);
Zm2=Bn-(Bm2);

dBm=Bm2-Bm1;
%dBm1 is not needed.
dBm2=1/3* ((Bm2 - Bm0)^3 - (Bm1 - Bm0)^3)/2;
dBm3=1/4* ((Bm2 - Bm0)^4 - (Bm1 - Bm0)^4)/6;
dBm4=1/5* ((Bm2 - Bm0)^5 - (Bm1 - Bm0)^5)/24;
dBm5=1/6* ((Bm2 - Bm0)^6 - (Bm1 - Bm0)^6)/120;
dBm6=1/7* ((Bm2 - Bm0)^7 - (Bm1 - Bm0)^7)/720;

%Below are calculations for CDF at the target point Bn on next grid with respect to entire mth grid cell.
Integral1=(0.398942* exp(-((0.5* Zm1^2)/sigma0^2)) - 0.398942* exp(-((0.5* Zm2^2)/sigma0^2)))*sigma0;%Integral of Zp(Z)dZ term in by parts integration in G2.
Integral2=-Bn*(normcdf(Zm2,0,sigma0)-normcdf(Zm1,0,sigma0));    %Integral of p(Z)dZ term multiplied by -Bn in G2. 
Integral3=Bm2*normcdf(Zm2,0,sigma0)-Bm1*normcdf(Zm1,0,sigma0);  %The boundaries integral in by parts integration in G2.

Integral0=dPm.*Pm0n; % G1 group of terms in wilmott explanation.

IntegralCDF=Integral0+ ...  %Integral0 is Group1(G1) in the explanation on wilmott.
     pm0.*(+Integral1+Integral2+Integral3)-  Pm0n*pm0*dBm+ ... %This line is group2 or G2 in explanation.
     + 2* dpm0 * (dPm0ndZt*dZtdBm) *dBm2 + ...  %This line and lines below are G3 in explanation.
    + (3*d2pm0*(dPm0ndZt*dZtdBm) + 3*dpm0*(d2Pm0ndZt2*dZtdBm^2))*dBm3 + ...
    + (4*d3pm0*(dPm0ndZt*dZtdBm) + 6* d2pm0*(d2Pm0ndZt2*dZtdBm^2) + 4* dpm0 * (d3Pm0ndZt3*dZtdBm^3))*dBm4 + ...
    + (5*d4pm0*(dPm0ndZt*dZtdBm) + 10* d3pm0*(d2Pm0ndZt2*dZtdBm^2)+ 10* d2pm0*(d3Pm0ndZt3*dZtdBm^3) + 5* dpm0 * (d4Pm0ndZt4*dZtdBm^4))*dBm5 + ...
    + (6*d5pm0*(dPm0ndZt*dZtdBm) + 15* d4pm0*(d2Pm0ndZt2*dZtdBm^2)+ 20* d3pm0*(d3Pm0ndZt3*dZtdBm^3) + 15* d2pm0 * (d4Pm0ndZt4*dZtdBm^4)+ ...
    6* dpm0 * (d5Pm0ndZt5*dZtdBm^5)) * dBm6;

%I have multiplied derivatives w.r.t Zt with powers of dZtdBm in order to
%convert them to derivatives w.r.t Bm. Some of this is very inefficient and
%will change in next version.

%Below are calculations for PDF at the target point Bn on next grid with respect to entire mth grid cell.
%In all of the calculations below integrals ending with 1,2,3 as
%P1Integral1,P1Integral2 and P1Integral3 belong to by parts integration in
%group G2. And Integrals ending with 0 as in P1Integral0 belong to group
%G1.
P1Integral1=-(1/sigma0)*0.398942* ( exp(-((0.5* Zm1^2)/sigma0^2))* Zm1- ...
    exp(-((0.5* Zm2^2)/sigma0^2))* Zm2- ...
    1.25331* sigma0* erf((0.707107 *Zm1)/sigma0)+1.25331* sigma0* erf((0.707107 *Zm2)/sigma0));
P1Integral2=-Bn*(normpdf(Zm2,0,sigma0)-normpdf(Zm1,0,sigma0));
P1Integral3=Bm2*normpdf(Zm2,0,sigma0)-Bm1*normpdf(Zm1,0,sigma0);
P1Integral0=dPm.*pm0n;
IntegralD1CDF=P1Integral0+ ...  %Group G1 integral for PDF
    pm0.*(P1Integral1+P1Integral2+P1Integral3)-  pm0n*pm0*dBm + ... %Group G2 integrals for PDF.
    2* dpm0 * (d2Pm0ndZt2*dZtdBm) *dBm2 + ...     %Group G3 terms in this line and below.
    +(3*d2pm0*(d2Pm0ndZt2*dZtdBm) + 3*dpm0*(d3Pm0ndZt3*dZtdBm^2))*dBm3 + ...
    +(4*d3pm0*(d2Pm0ndZt2*dZtdBm) + 6* d2pm0*(d3Pm0ndZt3*dZtdBm^2) + 4* dpm0 * (d4Pm0ndZt4*dZtdBm^3))*dBm4 + ...
    + (5*d4pm0*(d2Pm0ndZt2*dZtdBm) + 10* d3pm0*(d3Pm0ndZt3*dZtdBm^2)+ 10* (d4Pm0ndZt4*dZtdBm^3) + 5* dpm0 * (d5Pm0ndZt5*dZtdBm^4))*dBm5 + ...
    + (6*d5pm0*(d2Pm0ndZt2*dZtdBm) + 15* d4pm0*(d3Pm0ndZt3*dZtdBm^2)+ 20* (d4Pm0ndZt4*dZtdBm^3) + 15* d2pm0 * (d5Pm0ndZt5*dZtdBm^4)+ 6* dpm0 * (d6Pm0ndZt6*dZtdBm^5)) * dBm6;

%Below are calculations for first derivative of PDF at the target point Bn on next time grid with respect to entire mth grid cell.

P2Integral1=(1/((sigma0)^3)).*exp((-0.5* Zm1^2-0.5* Zm2^2)/sigma0^2).* (exp((0.5* Zm2^2)/sigma0^2)* (0.398942* sigma0^2+0.398942* Zm1^2)+...
    exp((0.5* Zm1^2)/sigma0^2)* (-0.398942* sigma0^2 - 0.398942* Zm2^2));

P2Integral2=-Bn*(-Zm2/sigma0/sigma0*normpdf(Zm2,0,sigma0)-(-Zm1)/sigma0^2*normpdf(Zm1,0,sigma0));
P2Integral3=Bm2*-Zm2/sigma0/sigma0*normpdf(Zm2,0,sigma0)-Bm1*(-Zm1)/sigma0^2*normpdf(Zm1,0,sigma0);
%PPIntegral0=dPm.*dpm0n;
P2Integral0=dPm.*d2Pm0ndZt2;
IntegralD2CDF=P2Integral0+ ... % Group G1 integral for first derivative of PDF
    pm0 * (P2Integral1+P2Integral2+P2Integral3)-  (d2Pm0ndZt2)*pm0*dBm+ ... %Group G2 integral terms for first derivative of PDF
    + (2* dpm0 * (d3Pm0ndZt3*dZtdBm)) *dBm2 + ...  %Group G3 terms in this line and below
    + (3*d2pm0*(d3Pm0ndZt3*dZtdBm) + 3*dpm0*(d4Pm0ndZt4*dZtdBm^2))*dBm3 + ...
    + (4*d3pm0*(d3Pm0ndZt3*dZtdBm) + 6* d2pm0*(d4Pm0ndZt4*dZtdBm^2) + 4* dpm0 * (d5Pm0ndZt5*dZtdBm^3))*dBm4 + ...
    + (5*d4pm0*(d3Pm0ndZt3*dZtdBm) + 10* d3pm0*(d4Pm0ndZt4*dZtdBm^2)+ 10* d2pm0*(d5Pm0ndZt5*dZtdBm^3) + 5* dpm0 * (d6Pm0ndZt6*dZtdBm^4))*dBm5 + ...
    + (6*d5pm0*(d3Pm0ndZt3*dZtdBm) + 15* d4pm0*(d4Pm0ndZt4*dZtdBm^2)+ 20* d3pm0*(d5Pm0ndZt5*dZtdBm^3) + 15* d2pm0 * (d6Pm0ndZt6*dZtdBm^4)+ 6* dpm0 * (d7Pm0ndZt7*dZtdBm^5)) * dBm6;

%Below are calculations for second derivative of PDF at the target point Bn on next time grid with respect to entire mth grid cell.

P3Integral1=(1/(sigma0^6))*sigma0* (-0.398942* exp(-((0.5* Zm1^2)/sigma0^2))* Zm1^3+  ...
    0.398942* exp(-((0.5* Zm2^2)/sigma0^2))* Zm2^3+sigma0^3 *(1.5* erf((0.707107* Zm1)/sigma0)- ...
    1.5* erf((0.707107* Zm1)/sigma0)-1.5* erf((0.707107* Zm2)/sigma0)+ ...
    1.5* erf((0.707107* Zm2)/sigma0)));
P3Integral2=-Bn*(((Zm2/sigma0)^2-1)/sigma0^2*normpdf(Zm2,0,sigma0)-((Zm1/sigma0)^2-1)/sigma0^2*normpdf(Zm1,0,sigma0));
P3Integral3=Bm2*((Zm2/sigma0)^2-1)/sigma0^2*normpdf(Zm2,0,sigma0)-Bm1*((Zm1/sigma0)^2-1)/sigma0^2*normpdf(Zm1,0,sigma0);
P3Integral0=dPm.*d3Pm0ndZt3;

IntegralD3CDF=P3Integral0+ ... %G1 integral for d2pdf
    pm0 * (P3Integral1+P3Integral2+P3Integral3)-  (d3Pm0ndZt3)*pm0*dBm+ ... %Group G2 terms for d2pdf
    + (2* dpm0 * (d4Pm0ndZt4*dZtdBm)) *dBm2 + ...  %G3 terms below
    + (3*d2pm0*(d4Pm0ndZt4*dZtdBm) + 3*dpm0*(d5Pm0ndZt5*dZtdBm^2))*dBm3 + ...
    + (4*d3pm0*(d4Pm0ndZt4*dZtdBm) + 6* d2pm0*(d5Pm0ndZt5*dZtdBm^2) + 4* dpm0 * (d6Pm0ndZt6*dZtdBm^3))*dBm4 + ...
    + (5*d4pm0*(d4Pm0ndZt4*dZtdBm) + 10* d3pm0*(d5Pm0ndZt5*dZtdBm^2)+ 10* d2pm0*(d6Pm0ndZt6*dZtdBm^3) + 5* dpm0 * (d7Pm0ndZt7*dZtdBm^4))*dBm5 + ...
    + (6*d5pm0*(d4Pm0ndZt4*dZtdBm) + 15* d4pm0*(d5Pm0ndZt5*dZtdBm^2)+ 20* d3pm0*(d6Pm0ndZt6*dZtdBm^3) + 15* d2pm0 * (d7Pm0ndZt7*dZtdBm^4)+ 6* dpm0 * (d8Pm0ndZt8*dZtdBm^5)) * dBm6;


%Below are calculations for third derivative of PDF at the target point Bn on next time grid with respect to entire mth grid cell.

P4Integral1=(1/(sigma0^8* sigma0))*(exp(-((0.5* Zm1^2)/sigma0^2))* (-0.398942* sigma0^6-0.797885* sigma0^4* Zm1^2+ ...
    0.398942* sigma0^2* Zm1^4)+exp(-((0.5* Zm2^2)/sigma0^2))* (0.398942* sigma0^6+0.797885* sigma0^4* Zm2^2-0.398942* sigma0^2* Zm2^4));
P4Integral2=-Bn*(((Zm2/sigma0)^3-3*(Zm2/sigma0))/sigma0^3*normpdf(Zm2,0,sigma0)-((Zm1/sigma0)^3-3*(Zm1/sigma0))/sigma0^3*normpdf(Zm1,0,sigma0));
P4Integral3=Bm2*((Zm2/sigma0)^3-3*(Zm2/sigma0))/sigma0^3*normpdf(Zm2,0,sigma0)-Bm1*((Zm1/sigma0)^3-3*(Zm1/sigma0))/sigma0^3*normpdf(Zm1,0,sigma0);
P4Integral0=dPm.*d4Pm0ndZt4;

IntegralD4CDF=P4Integral0+ ... %Group G1 terms for d3pdf 
    pm0 * (P4Integral1+P4Integral2+P4Integral3)-  (d4Pm0ndZt4)*pm0*dBm+ ...%Group G2 terms for d3pdf
    + (2* dpm0 * (d5Pm0ndZt5*dZtdBm)) *dBm2 + ...  %Group G3 terms for d3pdf
    + (3*d2pm0*(d5Pm0ndZt5*dZtdBm) + 3*dpm0*(d6Pm0ndZt6*dZtdBm^2))*dBm3 + ...
    + (4*d3pm0*(d5Pm0ndZt5*dZtdBm) + 6* d2pm0*(d6Pm0ndZt6*dZtdBm^2) + 4* dpm0 * (d7Pm0ndZt7*dZtdBm^3))*dBm4 + ...
    + (5*d4pm0*(d5Pm0ndZt5*dZtdBm) + 10* d3pm0*(d6Pm0ndZt6*dZtdBm^2)+ 10* d2pm0*(d7Pm0ndZt7*dZtdBm^3) + 5* dpm0 * (d8Pm0ndZt8*dZtdBm^4))*dBm5 + ...
    + (6*d5pm0*(d5Pm0ndZt5*dZtdBm) + 15* d4pm0*(d6Pm0ndZt6*dZtdBm^2)+ 20* d3pm0*(d7Pm0ndZt7*dZtdBm^3) + 15* d2pm0 * (d8Pm0ndZt8*dZtdBm^4)+ 6* dpm0 * (d9Pm0ndZt9*dZtdBm^5)) * dBm6;

Pmn=IntegralCDF;
pmn=IntegralD1CDF;
dpmn=IntegralD2CDF;
d2pmn=IntegralD3CDF;
d3pmn=IntegralD4CDF;

end
.
Here is the function to solve quartic equations. Root selection is in another function module that I will post tomorrow.
.
function [x1,x2,x3,x4] =SolveQuarticRootMathematica(a,b,c,d,e)
%solves a X^4+ b X^3+c X^2 + d X +e=0;


AA=(c^2-3* b* d+12* a* e);
BB=2* c^3-9* b* c* d+27* a* d^2+27* b^2* e-72* a* c* e;
CC=sqrt(-4* AA^3+BB^2);
DD=(BB+CC)^(1/3);
EE=(2^(1/3).* AA)/(3* a* DD);
FF=1/(3* 2^(1/3)* a)*(DD);
GG=sqrt(b^2/(4 *a^2)-(2* c)/(3* a)+EE+FF);
GG1=(-(b^3/a^3)+(4* b* c)/a^2-(8* d)/a)/(4* GG);
GG2=b^2/(2* a^2)-(4* c)/(3* a);
HH1=1/2*sqrt(GG2-EE- FF+ GG1);
HH2=1/2*sqrt(GG2-EE- FF- GG1);
II=-(b/(4* a));

x1=II+1/2* GG+HH1;
x2=II+1/2* GG-HH1;
x3=II-1/2* GG-HH2;
x4=II-1/2* GG+HH2;


%Below is the mathematica expression for roots.
%{{x->-(b/(4 a))-1/2 \[Sqrt](b^2/(4 a^2)-(2 c)/(3 a)+(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))+1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+Sqrt[-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2])^(1/3)))-1/2 \[Sqrt](b^2/(2 a^2)-(4 c)/(3 a)-(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))-1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+Sqrt[-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2])^(1/3))-(-(b^3/a^3)+(4 b c)/a^2-(8 d)/a)/(4 \[Sqrt](b^2/(4 a^2)-(2 c)/(3 a)+(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))+1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3)))))},
% {x->-(b/(4 a))-1/2 \[Sqrt](b^2/(4 a^2)-(2 c)/(3 a)+(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))+1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+Sqrt[-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2])^(1/3)))+1/2 \[Sqrt](b^2/(2 a^2)-(4 c)/(3 a)-(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))-1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+Sqrt[-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2])^(1/3))-(-(b^3/a^3)+(4 b c)/a^2-(8 d)/a)/(4 \[Sqrt](b^2/(4 a^2)-(2 c)/(3 a)+(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))+1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3)))))},
% {x->-(b/(4 a))+1/2 \[Sqrt](b^2/(4 a^2)-(2 c)/(3 a)+(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))+1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+Sqrt[-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2])^(1/3)))-1/2 \[Sqrt](b^2/(2 a^2)-(4 c)/(3 a)-(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))-1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+Sqrt[-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2])^(1/3))+(-(b^3/a^3)+(4 b c)/a^2-(8 d)/a)/(4 \[Sqrt](b^2/(4 a^2)-(2 c)/(3 a)+(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))+1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3)))))},
% {x->-(b/(4 a))+1/2 \[Sqrt](b^2/(4 a^2)-(2 c)/(3 a)+(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))+1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+Sqrt[-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2])^(1/3)))+1/2 \[Sqrt](b^2/(2 a^2)-(4 c)/(3 a)-(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))-1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+Sqrt[-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2])^(1/3))+(-(b^3/a^3)+(4 b c)/a^2-(8 d)/a)/(4 \[Sqrt](b^2/(4 a^2)-(2 c)/(3 a)+(2^(1/3) (c^2-3 b d+12 a e))/(3 a (2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3))+1/(3 2^(1/3) a)((2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e+\[Sqrt](-4 (c^2-3 b d+12 a e)^3+(2 c^3-9 b c d+27 a d^2+27 b^2 e-72 a c e)^2))^(1/3)))))}}

end
.
Following is the function that compares analytical and numerical results for integration by parts integrals in Group G2 in previous post. And compare the result of Analytic integration of(non-probability weighted meaning not multiplied with pdf of originating subdivision) transition CDF over a subdivision  compared with numerical integration of CDF.
.
function [] = CheckCDFfromSubdiv(Bn,Bm0,dB,sigma0)
%This function integrates gaussian transition CDF(to target point Bn) over 
%a subdivision with centre Bm0 and symmetric boundaries Bm1=Bm0-.5*dB; and 
%Bm2=Bm0+.5*dB;
%And compares it with integration by parts expression

Bm1=Bm0-.5*dB;
Bm2=Bm0+.5*dB;
dBm=(Bm2-Bm1)/10000;
Integral0=0;
for n=1:10001
    if(n==1)
        BmI=Bm1+(n-1)*dBm;
        Integral0=Integral0+.5*normcdf(Bn-BmI,0,sigma0)*dBm;
    end
    if((n>1)&&(n<10001))
        BmI=Bm1+(n-1)*dBm;
        Integral0=Integral0+normcdf(Bn-BmI,0,sigma0)*dBm;
    end
    if((n==10001))
        BmI=Bm1+(n-1)*dBm;
        Integral0=Integral0+.5*normcdf(Bn-BmI,0,sigma0)*dBm;
    end
end
        
%Analytic Integration of CDF over a subdivision using by parts integration 
%as we solved for terms in Group G2.

Zm1=Bn-(Bm1);
Zm2=Bn-(Bm2);

Integral1=(0.398942* exp(-((0.5* Zm1^2)/sigma0^2)) - 0.398942* exp(-((0.5* Zm2^2)/sigma0^2)))*sigma0;
Integral2=-Bn*(normcdf(Zm2,0,sigma0)-normcdf(Zm1,0,sigma0));
Integral3=Bm2*normcdf(Zm2,0,sigma0)-Bm1*normcdf(Zm1,0,sigma0);
%Integral1
%Integral2
AnalyticResult=Integral3+Integral1+Integral2
NumericalResult=Integral0
end

 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 9th, 2021, 1:22 pm

Friends, I was totally unexpectedly detained by people from a psychiatrist facility on Friday evening. The psychiatrist was very kind to give me my computer and give me access to internet. I will be posting the uncommented program that I had promised in less than an hour. And post a commented program later since I do not want to take any risk of not being able to post even the uncommented program(due to something unforeseen.). 
I also want to tell friends that posting on this forum from my computer and my phone is blocked by spmhaus.org due to "bad reputation". When I try VPN, unidentified network connection takes over and does not allow me to connect to VPN through my internet or internet at "tree house", the psychiatric facility where I am detained.
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 9th, 2021, 1:41 pm

Post in progress.
The night I was detained, I tried to post on internet from my phone and was surprised that my ability to write on wilmott forum was blocked due to spamhaus.org despite that I use my phone for internet extremely rarely and almost never for posting except that I used my phone once or twice on wilmott. The next day, they took my cell phone and I could not do anything. 
Coming to business again, I will be posting uncommented program in less than half an hour.
It seems that despite being logged in, I cannot edit my previous posts.
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 9th, 2021, 2:03 pm

Post in progress.
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 9th, 2021, 2:25 pm

Here is the main program with all functions(some you may have to copy from old posts.) I will post a complete commented version in a day after this. I hope things go well for me. I will request American friends to please force mind control agency to end my detention.
.
function [] = SDETransProb08WmtGrid200b40()

%Copyright Ahsan Amin. Infiniti derivatives Technologies.
%Please fell free to connect on linkedin: linkedin.com/in/ahsan-amin-0a53334 
%or skype ahsan.amin2999
%In this program, I am simulating the SDE given as
%dy(t)=mu1 x(t)^beta1 dt + mu2 x(t)^beta2 dt +sigma x(t)^gamma dz(t)

%I have not directly simulated the SDE but simulated the transformed 
%Besse1 process version of the SDE and then changed coordinates to retreive
%the SDE in original coo
%rdinates.
%The present program will analytically evolve only the Bessel Process version of the
%SDE in transformed coordinates.
%When you run this program, please make sure that you look at graph zoomed
%at main body of the graph. Sometimes all the SDE is properly simulated but
%the tail explodes for some reason so you would know. These are minor
%issues that will be fixed in next versions of the program.
%I have put the terminal date at a very small value. Since calculations are
%done for all possible pairs of covariances on a very large number of time
%steps, increasing time to a large value is going to take quite a while.
%Start with a small date. You might want to modify this algorithm to
%calculate covariance pairs certain time spacing larger than minimum time spacing. 
T=1/16;

dt=.125/16/2/2/2;   % Simulation time interval.%Fodiffusions close to zero
             %decrease dt for accuracy.
Tt=T*128*2*2*2;     % Number of simulation levels. Terminal time= Tt*dt; //.125/32*32*16=2 year; 
%T=Tt*dt;
Tt=17;

OrderA=4;  %
dtM=dt;%.125/2/4;%Monte carlo time interval size dtM.
TtM=Tt;%T*2*8*4;%Monte carlo number of simulation intervals.



dNn=.05;   % Normal density subdivisions width. would change with number of subdivisions
Nn=200;  % No of normal density subdivisions
NnMidl=100;%One half density Subdivision left from mid of normal density(low)
NnMidh=101;%One half density subdivision right from the mid of normal density(high)
NnMid=4.0;

Z(1:Nn)=(((1:Nn)-20.5)*dNn-NnMid)


Nn1=240;
%dNn1=.05;
Nn1Midl=120;
Nn1Midh=121;
Nn1Mid=6.025;





Nn2=230;
%dNn2=.05;
Nn2Midl=115;
Nn2Midh=116;
Nn2Mid=5.775;
Z2(1:Nn2)=((1:Nn2)*dNn-Nn2Mid)


Nn3=220;
%dNn3=.05;
Nn3Midl=110;
Nn3Midh=111;
Nn3Mid=5.525;
Z3(1:Nn3)=((1:Nn3)*dNn-Nn3Mid)


Nn4=210;
%dNn4=.05;
Nn4Midl=105;
Nn4Midh=106;
Nn4Mid=5.275;
Z4(1:Nn4)=((1:Nn4)*dNn-Nn4Mid)

Z1(1:Nn1)=((1:Nn1)*dNn-Nn1Mid)
Z1Prob(1)=normcdf(-5.95)-normcdf(-6.0);
Z1Prob(Nn1)=normcdf(6.0)-normcdf(5.95);
Z1Prob(2:Nn1-1)=normcdf(.5*Z1(2:Nn1-1)+.5*Z1(3:Nn1),0,1)-normcdf(.5*Z1(2:Nn1-1)+.5*Z1(1:Nn1-2),0,1);

Z2Prob(1:Nn2)=Z1Prob(6:Nn1-5);
Z3Prob(1:Nn3)=Z1Prob(11:Nn1-10);
Z4Prob(1:Nn4)=Z1Prob(16:Nn1-15);
ZProb(1:Nn)=Z1Prob(21:Nn1-20);
Z(1:Nn)=Z1(21:Nn1-20);


sum(Z1Prob(1:Nn1))
sum(Z2Prob(1:Nn2))
sum(Z3Prob(1:Nn3))
sum(Z4Prob(1:Nn4))
sum(ZProb(1:Nn))
str=input('Look at Zs');

x0=.100;   % starting value of SDE
beta1=0.0;
beta2=1.00;   % Second drift term power.
gamma=.5;%50;   % volatility power.                                                                                                                                                                                                                                                                     
kappa=2.0;%.950;   %mean reversion parameter.
theta=1.0;%mean reversion target
sigma0=.850;%Volatility value

%you can specify any general mu1 and mu2 and beta1 and beta2.
mu1=+1*theta*kappa;   %first drift coefficient.
mu2=-1*kappa;    % Second drift coefficient.
%mu1=0;
%mu2=0;

alpha=1;% x^alpha is being expanded. This is currently for monte carlo only.
alpha1=1-gamma;%This is for expansion of integrals for calculation of drift 
%and volatility coefficients
                
w(1:Nn)=x0^(1-gamma)/(1-gamma);

%Z(1:Nn)=(((1:Nn)-5.5)*dNn-NnMid);
%Z(1:Nn)=(((1:Nn)-20.5)*dNn-NnMid);
%Z(1:Nn)=(((1:Nn)-20.5)*dNn-NnMid);






%Z(1)=-5.118453;
%Z(Nn)=5.118453;

%Z2(1:Nn2)=(((1:Nn2)-60.5)*dNn-Nn2Mid);

Z
Z2
str=input('Look at Zs')
%ZProb(1)=normcdf(.5*Z(1)+.5*Z(2),0,1)-normcdf(.5*Z(1)+.5*Z(2)-dNn,0,1);
%ZProb(Nn)=normcdf(.5*Z(Nn)+.5*Z(Nn-1)+dNn,0,1)-normcdf(.5*Z(Nn)+.5*Z(Nn-1),0,1);
%ZProb(2:Nn-1)=normcdf(.5*Z(2:Nn-1)+.5*Z(3:Nn),0,1)-normcdf(.5*Z(2:Nn-1)+.5*Z(1:Nn-2),0,1);
    %Above calculate probability mass in each probability subdivision.
    
%ZProb(1)=normcdf(-4.95);
%ZProb(Nn)=1-normcdf(4.95);
%ZProb(2)=normcdf(-4.9)-normcdf(-4.95);
%ZProb(Nn-1)=normcdf(4.95)-normcdf(4.9);
%ZProb(3:Nn-2)=normcdf(.5*Z(3:Nn-2)+.5*Z(4:Nn-1),0,1)-normcdf(.5*Z(3:Nn-2)+.5*Z(2:Nn-3),0,1);


%ZProb2(1)=normcdf(-6.95);
%ZProb2(Nn2)=1-normcdf(6.95);
%ZProb2(2)=normcdf(-6.9)-normcdf(-6.95);
%ZProb2(Nn2-1)=normcdf(6.95)-normcdf(6.9);
%ZProb2(3:Nn2-2)=normcdf(.5*Z2(3:Nn2-2)+.5*Z2(4:Nn2-1),0,1)-normcdf(.5*Z2(3:Nn2-2)+.5*Z2(2:Nn2-3),0,1);

%ZProb2
str=input('Look ar Zprob2');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

sigma11(1:OrderA+1)=0;
mu11(1:OrderA+1)=0;
mu22(1:OrderA+1)=0;
sigma22(1:OrderA+1)=0;
% index 1 correponds to zero level since matlab indexing starts at one. 
sigma11(1)=1;
mu11(1)=1;
mu22(1)=1;
sigma22(1)=1;


mu33(1)=1;
mu44(1)=1;
mu33(2:OrderA+1)=0;
mu44(2:OrderA+1)=0;

for k=1:(OrderA+1)
    if sigma0~=0
        sigma11(k)=sigma0^(k-1);
    end
    if mu1 ~= 0
        mu11(k)=mu1^(k-1);
    end
    if mu2 ~= 0
        mu22(k)=mu2^(k-1);
    end
    if sigma0~=0
        sigma22(k)=sigma0^(2*(k-1));
    end
end
%Ft(1:TtM+1,1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0; %General time powers on hermite polynomials
Fp(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;%General x powers on coefficients of hermite polynomials.
Fp1(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;%General x powers for bessel transformed coordinates.

%YCoeff0 and YCoeff are coefficents for original coordinates monte carlo.
%YqCoeff0 and YqCoeff are bessel/lamperti version monte carlo.

YCoeff0(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;
YqCoeff0(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;
%Pre-compute the time and power exponent values in small multi-dimensional arrays
YCoeff = ItoTaylorCoeffsNew(alpha,beta1,beta2,gamma); %expand y^alpha where alpha=1;
YqCoeff = ItoTaylorCoeffsNew(alpha1,beta1,beta2,gamma);%expand y^alpha1 where alpha1=(1-gamma)
YqCoeff=YqCoeff/(1-gamma); %Transformed coordinates coefficients have to be 
%further divided by (1-gamma)

for k = 0 : (OrderA)
    for m = 0:k
        l4 = k - m + 1;
        for n = 0 : m
            l3 = m - n + 1;
            for j = 0:n
                l2 = n - j + 1;
                l1 = j + 1;
                %Ft(l1,l2,l3,l4) = dtM^((l1-1) + (l2-1) + (l3-1) + .5* (l4-1));
                Fp(l1,l2,l3,l4) = (alpha + (l1-1) * beta1 + (l2-1) * beta2 + (l3-1) * 2* gamma + (l4-1) * gamma ...
                    - (l1-1) - (l2-1) - 2* (l3-1) - (l4-1));
                Fp1(l1,l2,l3,l4) = (alpha1 + (l1-1) * beta1 + (l2-1) * beta2 + (l3-1) * 2* gamma + (l4-1) * gamma ...
                    - (l1-1) - (l2-1) - 2* (l3-1) - (l4-1));
                
                YCoeff0(l1,l2,l3,l4) =YCoeff(l1,l2,l3,l4).*mu11(l1).*mu22(l2).*sigma22(l3).*sigma11(l4);
                YqCoeff0(l1,l2,l3,l4) =YqCoeff(l1,l2,l3,l4).*mu11(l1).*mu22(l2).*sigma22(l3).*sigma11(l4);
                YqzCoeff0(l1,l2,l3,l4) =YqCoeff(l1,l2,l3,l4).*mu33(l1).*mu44(l2).*sigma22(l3).*sigma11(l4);
            end
        end
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Current program has 50 grid points. I have divided every grid subdivision
%into three further subdivisions with probabilities P0,Pb,Pa.
 

wnStart=1;%
yy(wnStart:Nn)=((1-gamma)*w(wnStart:Nn)).^(1/(1-gamma));
%The above yy(wnStart:Nn)=x0;

tic

% load('C:\\Users\\Ahsan\\Documents\\MATLAB\\TrProbs0O4b.mat','pt0','Zt0');
% load('C:\\Users\\Ahsan\\Documents\\MATLAB\\TrProbsO4b.mat','ptt','Ztt','ptA','ptB');

%load('C:\\Users\\Ahsan\\Documents\\MATLAB\\TrProbs0O4.mat','pt0','Zt0');
%load('C:\\Users\\Ahsan\\Documents\\MATLAB\\TrProbsO4.mat','ptt','Ztt','ptA','ptB');
%load('C:\\Users\\Ahsan\\Documents\\MATLAB\\FPEwI.mat','wI');
%load('C:\\Users\\Ahsan\\Documents\\MATLAB\\FPEdwZI.mat','dwZI');
for tt=1:Tt 
    t2=tt*dt;
    t1=(tt-1)*dt;
    if(tt==1)
        
        
       
        [wMu0dt,c1,c22] = CalculateDriftAndVolA8Trans(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt);
        w(1:Nn)=x0^(1-gamma)/(1-gamma)+wMu0dt(1)+c1(1).*Z(1:Nn);
        
        
        %[w1Mu0dt,c1wz,c22wz] = CalculateDriftAndVolA8Trans(w,wnStart,Nn,YqzCoeff0,Fp1,gamma,dt);
        %Ew1new(1:Nn2)=(x0^(1-gamma)/(1-gamma)+w1Mu0dt(1)+c1wz(1).*Zt0(1:Nn2)+c22(1).*(Zt0(1:Nn2).^2-1)).*pt0(1:Nn2);

        %w1ZdwdZ(1:Nn)=sigma0*sqrt(dt);
    end
    if((tt>1) && (tt<=16))
        [wMu0dt,wMu1dt,dwMu0dtdw,d2wMu0dtdw2,c1] = CalculateDriftAndVolA404(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt);
        %dw(wnStart:Nn)=c1(wnStart:Nn);%.*Z(wnStart:Nn) ;% ...
        dw(wnStart:Nn)=c1(wnStart:Nn).*Z(wnStart:Nn) ;% ...
        dw2(wnStart:Nn)=dw(wnStart:Nn).^2;
        [wMid] = InterpolateOrderN8(8,0,Z(NnMidl-3),Z(NnMidl-2),Z(NnMidl-1),Z(NnMidl),Z(NnMidh),Z(NnMidh+1),Z(NnMidh+2),Z(NnMidh+3),w(NnMidl-3),w(NnMidl-2),w(NnMidl-1),w(NnMidl),w(NnMidh),w(NnMidh+1),w(NnMidh+2),w(NnMidh+3));
        B(1:Nn)=w(1:Nn)-wMid;
       [dBdZ,d2BdZ2,d3BdZ3] = First3Derivatives2ndOrderEqSpacedA(wnStart,Nn,dNn,B,Z);
       B(wnStart:Nn)=sign(B(wnStart:Nn)+dw(wnStart:Nn)).* ...
            sqrt(abs(sign(B(wnStart:Nn)).*(B(wnStart:Nn)).^2+ ...
            sign(dw(wnStart:Nn)).*dw2(wnStart:Nn)));
       %B(NnMidh)=sqrt(dBdZ(NnMidh).^2+ dw2(NnMidh)).*dNn/2;
       %Bb(NnMidh)=2*B(NnMidh);
       %for nn=NnMidh+1:Nn
        
       % dB=sqrt(dBdZ(nn).^2+ dw2(nn)).*dNn/2;
       % B(nn)=Bb(nn-1)+dB ;
       % Bb(nn)=Bb(nn-1)+2*dB;
       %end
        
       %B(NnMidl)=sqrt(dBdZ(NnMidl).^2+ dw2(NnMidl)).*-dNn/2;
       %Bb(NnMidl)=2*B(NnMidl);
       %for nn=NnMidl-1:-1:wnStart
       
       % dB=sqrt(dBdZ(nn).^2+ dw2(nn)).*dNn/2;
       % B(nn)=Bb(nn+1)-dB ;
       % Bb(nn)=Bb(nn+1)-2*dB;
       % end
            %sqrt(abs(sign(B(wnStart:Nn)).*(B(wnStart:Nn)).^2+ ...
            %sign(dw(wnStart:Nn)).*dw2(wnStart:Nn)));
        
        
        w(wnStart:Nn)=wMid+wMu0dt(wnStart:Nn)+B(wnStart:Nn);
        
        
        
    end
    
    if(tt>16)
                
       [wMu0dt,wMu1dt,dwMu0dtdw,d2wMu0dtdw2,c1] = CalculateDriftAndVolA404(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt); 
       %dw(wnStart:Nn)=c1(wnStart:Nn).*Z(wnStart:Nn) ;% ...
       dw(wnStart:Nn)=c1(wnStart:Nn) ;% ...
       dw2(wnStart:Nn)=dw(wnStart:Nn).^2;
       %[wMid] = InterpolateOrderN6(6,0,Z(NnMidl-2),Z(NnMidl-1),Z(NnMidl),Z(NnMidh),Z(NnMidh+1),Z(NnMidh+2),w(NnMidl-2),w(NnMidl-1),w(NnMidl),w(NnMidh),w(NnMidh+1),w(NnMidh+2));
       [wMid] = InterpolateOrderN8(8,0,Z(NnMidl-3),Z(NnMidl-2),Z(NnMidl-1),Z(NnMidl),Z(NnMidh),Z(NnMidh+1),Z(NnMidh+2),Z(NnMidh+3),w(NnMidl-3),w(NnMidl-2),w(NnMidl-1),w(NnMidl),w(NnMidh),w(NnMidh+1),w(NnMidh+2),w(NnMidh+3));
       B(1:Nn)=w(1:Nn)-wMid;
       B1=B;
       [dBdZ_0,d2BdZ2_0,d3BdZ3_0] = First3Derivatives2ndOrderEqSpacedA(wnStart,Nn,dNn,B,Z);
       
 %      dZdB(1:Nn)=1.0./dBdZ(1:Nn);
 %      d2ZdB2(1:Nn)=-d2BdZ2(1:Nn).*dZdB(1:Nn).^3;
 
 %d3ZdB3(1:Nn)=-d3BdZ3(1:Nn).*dZdB(1:Nn).^4+3*d2BdZ2(1:Nn).^2.*dZdB(1:Nn).^5;
 
 %d4ZdB4(1:Nn)=0.0;
       
       
       
       

       
       
       
       
            %[GridStarts,GridEnds] = CalculateGridStartsAndEndsBoundedEnds(w,Z,wnStart,Nn,dNn);
       %[B1a,B1b] = CalculateGridStartsAndEndsBoundedEnds(B1,Z,wnStart,Nn,dNn);
       
       if(tt<=32)
            for nn=1:20
                xx0(nn)=Z(1)-nn*dNn;
                xx1(nn)=Z(nn);
                %%yy1(nn)=dBdZ_0(nn);
                yy1(nn)=B1(nn);
            end
            %%[yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            %%Btemp=B1(1);
            for nn=1:20
                BB1(21-nn)=yy0(nn);
                %%BB1(21-nn)=Btemp-yy0(nn)*dNn;
                %%Btemp=BB1(21-nn);
            end
            for nn=1:Nn
                BB1(nn+20)=B1(nn);
            end
            for nn=1:20
                xx0(nn)=Z(Nn)+nn*dNn;
                xx1(nn)=Z(Nn-nn+1);
                %%yy1(nn)=dBdZ_0(Nn-nn+1);
                yy1(nn)=B1(Nn-nn+1);
            end
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            %%Btemp=B1(Nn);
            for nn=1:20
                BB1(Nn+20+nn)=yy0(nn);
                %BB1(Nn+20+nn)=Btemp+yy0(nn)*dNn;
                %Btemp=BB1(Nn+20+nn);
            end
            
            [BB1a,BB1b] = CalculateGridStartsAndEndsBoundedEnds(BB1,Z1,1,Nn1,dNn);
            
            
            
            
            ZZ1=Z1;
            NN1=Nn1;
            ZZProb(1:NN1)=Z1Prob(1:Nn1);
        
            plot(ZZ1(1:NN1),BB1(1:NN1),'b',ZZ1(1:NN1),BB1a(1:NN1),'y',ZZ1(1:NN1),BB1b(1:NN1),'k',Z(1:Nn),B1(1:Nn),'r')
            str=input('Look at B1 and BB1');
            
            [dBdZ,d2BdZ2,d3BdZ3] = First3Derivatives2ndOrderEqSpacedA(1,NN1,dNn,BB1,Z1);
            [dwdZAA,d2wdZ2AA,d3wdZ3AA,d4BdZ4] = First4Derivatives2ndOrderEqSpaced(1,NN1,dNn,BB1,Z1)
        
        plot((1:NN1),dBdZ(1:NN1),'r')
        str=input('Look at 1st derivative');
        plot((1:NN1),d2BdZ2(1:NN1),'r')
        str=input('Look at 2nd derivative');
        plot((1:NN1),d3BdZ3(1:NN1),'r')
        str=input('Look at 3rd derivative');
        
        
       
       He1(1:NN1)=Z1(1:NN1);
       He2(1:NN1)=Z1(1:NN1).^2-1;
       He3(1:NN1)=Z1(1:NN1).^3-3*Z1(1:NN1);
       He4(1:NN1)=Z1(1:NN1).^4-6*Z1(1:NN1).^2+3;
       He5(1:NN1)=Z1(1:NN1).^5-10*Z1(1:NN1).^3+15;
       Zpdf(1:NN1)=normpdf(Z1(1:NN1),0,1);
       dZpdf(1:NN1)=-He1(1:NN1).*Zpdf(1:NN1);
       d2Zpdf(1:NN1)=He2(1:NN1).*Zpdf(1:NN1);
       d3Zpdf(1:NN1)=-He3(1:NN1).*Zpdf(1:NN1);
       d4Zpdf(1:NN1)=He4(1:NN1).*Zpdf(1:NN1);
       d5Zpdf(1:NN1)=-He5(1:NN1).*Zpdf(1:NN1);

        
       dZdB(1:NN1)=1.0./dBdZ(1:NN1);
       d2ZdB2(1:NN1)=-d2BdZ2(1:NN1).*dZdB(1:NN1).^3;
       d3ZdB3(1:NN1)=-d3BdZ3(1:NN1).*dZdB(1:NN1).^4+3*d2BdZ2(1:NN1).^2.*dZdB(1:NN1).^5;
       d4ZdB4(1:NN1)=-d4BdZ4(1:NN1).*dZdB(1:NN1).^5-4*d3BdZ3(1:NN1).*d2ZdB2(1:NN1).*dZdB(1:NN1).^3+ ...
           6*d2BdZ2(1:NN1).*d3BdZ3(1:NN1).*dZdB(1:NN1).^6+15*d2BdZ2(1:NN1).^2.*d2ZdB2(1:NN1).*dZdB(1:NN1).^6 ;
       d5ZdB5(1:NN1)=0.0;
       d6ZdB6(1:NN1)=0.0;
       
       
            
          pm0(1:NN1)=Zpdf(1:NN1).*dZdB(1:NN1);
        dpm0(1:NN1)=dZpdf(1:NN1).*dZdB(1:NN1).^2+Zpdf(1:NN1).*d2ZdB2(1:NN1);
        d2pm0(1:NN1)=d2Zpdf(1:NN1).*dZdB(1:NN1).^3+3*dZpdf(1:NN1).*dZdB(1:NN1).*d2ZdB2(1:NN1)+Zpdf(1:NN1).*d3ZdB3(1:NN1);
        d3pm0(1:NN1)=d3Zpdf(1:NN1).*dZdB(1:NN1).^4+6*d2Zpdf(1:NN1).*dZdB(1:NN1).^2.*d2ZdB2(1:NN1) + ...
        4*dZpdf(1:NN1).*dZdB(1:NN1).*d3ZdB3(1:NN1) + 3*dZpdf(1:NN1).*d2ZdB2(1:NN1).^2+ Zpdf(1:NN1).*d4ZdB4(1:NN1);
    
        d4pm0(1:NN1)=d4Zpdf(1:NN1).*dZdB(1:NN1).^5+10*d3Zpdf(1:NN1).*dZdB(1:NN1).^3.*d2ZdB2(1:NN1) + ...
            +15*d2Zpdf(1:NN1).*dZdB(1:NN1).*d2ZdB2(1:NN1).^2 + ...
            +10*d2Zpdf(1:NN1).*dZdB(1:NN1).^2.*d3ZdB3(1:NN1) + ...
            10*dZpdf(1:NN1).*d2ZdB2(1:NN1).*d3ZdB3(1:NN1) + ...
            5*dZpdf(1:NN1).*dZdB(1:NN1).*d4ZdB4(1:NN1)+ Zpdf(1:NN1).*d5ZdB5(1:NN1);
        
        d5pm0(1:NN1)=d5Zpdf(1:NN1).*dZdB(1:NN1).^6+15*d4Zpdf(1:NN1).*dZdB(1:NN1).^4.*d2ZdB2(1:NN1) + ...
            +45*d3Zpdf(1:NN1).*dZdB(1:NN1).^2.*d2ZdB2(1:NN1).^2 + ...
            +20*d3Zpdf(1:NN1).*dZdB(1:NN1).^3.*d3ZdB3(1:NN1) + ...
            15*d2Zpdf(1:NN1).*d2ZdB2(1:NN1).^3 + ...
            60*d2Zpdf(1:NN1).*dZdB(1:NN1).*d2ZdB2(1:NN1).*d3ZdB3(1:NN1) + ...
            15*d2Zpdf(1:NN1).*d2ZdB2(1:NN1).^2.*d4ZdB4(1:NN1)+ ...
            10*dZpdf(1:NN1).*d3ZdB3(1:NN1).^2+ ...
            15*dZpdf(1:NN1).*d2ZdB2(1:NN1).*d4ZdB4(1:NN1)+ ...
            6*dZpdf(1:NN1).*dZdB(1:NN1).*d5ZdB5(1:NN1)+ ...
            Zpdf(1:NN1).*d6ZdB6(1:NN1);
   

            
       elseif (tt<=64)
            for nn=1:15
                xx0(nn)=Z(1)-nn*dNn;
                xx1(nn)=Z(nn);
                yy1(nn)=dBdZ(nn);
                yy1(nn)=dBdZ(nn);
            end
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            Btemp=B1(1);
            for nn=15:-1:1
                BB1(nn)=Btemp-yy0(nn);
                Btemp=BB1(nn);
            end
            for nn=1:Nn
                BB1(nn+15)=B1(nn);
            end
            for nn=1:15
                xx0(nn)=Z(Nn)+nn*dNn;
                xx1(nn)=Z(Nn-nn+1);
                yy1(nn)=dBdZ(Nn-nn+1);
            end
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            Btemp=B1(Nn); 
            for nn=1:15
                BB1(Nn+15+nn)=Btemp+yy0(nn);
                Btemp=BB1(Nn+15+nn);
            end
            
            [BB1a,BB1b] = CalculateGridStartsAndEndsBoundedEnds(BB1,Z2,1,Nn2,dNn);
            ZZ1=Z2;
            NN1=Nn2;
            ZZProb(1:NN1)=Z2Prob(1:Nn2);
           
           
        elseif (tt<=128)
            for nn=1:10
                xx0(nn)=Z(1)-nn*dNn;
                xx1(nn)=Z(nn);
                yy1(nn)=dBdZ(nn);
            end
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            Btemp=B1(1);
            for nn=10:-1:1
                BB1(nn)=Btemp-yy0(nn);
                Btemp=BB1(nn);
            end
            for nn=1:Nn
                BB1(nn+10)=B1(nn);
            end
            for nn=1:10
                xx0(nn)=Z(Nn)+nn*dNn;
                xx1(nn)=Z(Nn-nn+1);
                yy1(nn)=dBdZ(Nn-nn+1);
            end
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            Btemp=B1(Nn);
            for nn=1:10
                BB1(Nn+10+nn)=Btemp+yy0(nn);
                Btemp=BB1(Nn+10+nn);
            end
            
            [BB1a,BB1b] = CalculateGridStartsAndEndsBoundedEnds(BB1,Z3,1,Nn3,dNn);
            ZZ1=Z3;
            NN1=Nn3;
            ZZProb(1:NN1)=Z3Prob(1:Nn3);

       else
            for nn=1:5
                xx0(nn)=Z(1)-nn*dNn;
                xx1(nn)=Z(nn);
                yy1(nn)=dBdZ(nn);
            end
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            Btemp=B1(1);
            for nn=5:-1:1
                BB1(nn)=Btemp-yy0(nn);
                Btemp=BB1(nn);
            end
            for nn=1:Nn
                BB1(nn+5)=B1(nn);
            end
            for nn=1:5
                xx0(nn)=Z(Nn)+nn*dNn;
                xx1(nn)=Z(Nn-nn+1);
                yy1(nn)=dBdZ(Nn-nn+1);
            end
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            Btemp=B1(Nn);
            for nn=1:5
                BB1(Nn+5+nn)=Btemp+yy0(nn);
                Btemp=BB1(Nn+5+nn);
            end
            
            [BB1a,BB1b] = CalculateGridStartsAndEndsBoundedEnds(BB1,Z4,1,Nn4,dNn);
            ZZ1=Z4;
            NN1=Nn4;
            ZZProb(1:NN1)=Z4Prob(1:Nn4);
       end

       
       ww1(1:NN1)=BB1(1:NN1)+wMid;
       [wwMu0dt,wwMu1dt,wdwMu0dtdw,wd2wMu0dtdw2,cc1] = CalculateDriftAndVolA404(ww1,1,NN1,YqCoeff0,Fp1,gamma,dt); 
       plot(ZZ1(1:NN1),ww1(1:NN1),'b',Z(1:Nn),w(1:Nn),'r')
       str=input('Look at comparison of interpolated and original w-0');
       plot(ZZ1(1:NN1),cc1(1:NN1),'b',Z(1:Nn),c1(1:Nn),'r')
       str=input('Look at comparison of original and interpolated vol coefficient-1');
       plot(ZZ1(1:NN1),cc1(1:NN1),'b',Z(1:Nn),c1(1:Nn),'r')
       str=input('Look at comparison of original and interpolated vol coefficient-1A');
       %plot(ZZ1(1:NN1),BB1(1:NN1),'b')
       plot(ZZ1(1:NN1),wwMu0dt(1:NN1),'b',Z(1:Nn),wMu0dt(1:Nn),'r')
       str=input('Look at drifts origianl and interpolated-2');
       plot(ZZ1(1:NN1),ZZProb(1:NN1),'b',Z(1:Nn),ZProb(1:Nn),'r')
       str=input('Look at Zprobss -3');
       plot((1:Nn),Z(1:Nn),'r',(1:NN1)-20,ZZ1(1:NN1),'b')
       str=input('Look at Zs -4');
       
       
       dBdZ
       dw2
       str=input('Look at first derivative');
       B2a(NnMidh)=0.0;
       TotalExcessCDF2=0;
       for nn=NnMidh:Nn
           
            SigmaB(nn)=sqrt(dBdZ_0(nn).^2+ dw2(nn));
            if(nn==NnMidh)
                B3(nn)=SigmaB(nn).*dNn/2;
            else
                B3(nn)=B3(nn-1)+SigmaB(nn).*dNn;
            end
            
            
            B2(nn)=B2a(nn)+SigmaB(nn).*dNn/2;
            
            B2b(nn)=B2a(nn)+SigmaB(nn).*dNn;
            PIn(nn)=0;
            Pout(nn)=0;
            pout(nn)=0;
            dpoutdB(nn)=0.0;
            d2poutdB2(nn)=0.0;
            d3poutdB3(nn)=0.0;
            pin(nn)=0;
            dpindB(nn)=0.0;
            d2pindB2(nn)=0.0;
            d3pindB3(nn)=0.0;
            for mm=1:NN1
                %if(abs(B2b(nn)-BB1(mm))<8*cc1(mm))
                   
                   [Pmn] = CalculateCDFFromSubDiv(B2a(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));

                   
                    
                    %PIn(nn)=PIn(nn)+ ZZProb(mm).*normcdf((B2a(nn)-BB1(mm)),0,cc1(mm));
                    PIn(nn)=PIn(nn)+ Pmn;
                    %[Pmn,pmn,dpmn] = CalculateCDFAndDerivativesFromSubDiv(Bn,sigma0,Bm0,Bm1,Bm2,dPm,pm0,dpm0,d2pm0,d3pm0);
                   [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
                   dZdB(mm)
                   pm0(mm)
                   dpm0(mm)
                   d2pm0(mm) 
                   Pout(nn)=Pout(nn)+ Pmn;
                               %       Pout(nn)=Pout(nn)+ ZZProb(mm).*normcdf((B2b(nn)-BB1(mm)),0,cc1(mm));
                   Pmn            
                   ZZProb(mm).*normcdf((B2b(nn)-BB1(mm)),0,cc1(mm))
                   pmn
                   ZZProb(mm).*normpdf((B2b(nn)-BB1(mm)),0,cc1(mm))
                   dpmn
                   ZZProb(mm).*-(B2b(nn)-BB1(mm))/cc1(mm).^2.*normpdf((B2b(nn)-BB1(mm)),0,cc1(mm))
                   nn
                   mm
   %                str=input('Look at comparison of values');
                   %ptemp=ZZProb(mm).*normpdf((B2b(nn)-BB1(mm)),0,cc1(mm));
                   pout(nn)=pout(nn)+pmn;
                   dpoutdB(nn)=dpoutdB(nn)+dpmn;
                   d2poutdB2(nn)=d2poutdB2(nn)+d2pmn;
                   d3poutdB3(nn)=d3poutdB3(nn)+d3pmn;
                   
                   %d2poutdB2(nn)=d2poutdB2(nn)+ptemp*((B2b(nn)-BB1(mm)).^2./cc1(mm).^2-1)./cc1(mm).^2;
                   %d3poutdB3(nn)=d3poutdB3(nn)+ptemp*((B2b(nn)-BB1(mm)).^3./cc1(mm).^3-3*(B2b(nn)-BB1(mm))./cc1(mm))./cc1(mm).^3;
 
 
                    
                   
            %       Pout(nn)=Pout(nn)+ ZZProb(mm).*normcdf((B2b(nn)-BB1(mm)),0,cc1(mm));
            %       ptemp=ZZProb(mm).*normpdf((B2b(nn)-BB1(mm)),0,cc1(mm));
            %       pout(nn)=pout(nn)+ptemp;
            %       dpoutdB(nn)=dpoutdB(nn)+ptemp*-(B2b(nn)-BB1(mm))./cc1(mm).^2;
            %       d2poutdB2(nn)=d2poutdB2(nn)+ptemp*((B2b(nn)-BB1(mm)).^2./cc1(mm).^2-1)./cc1(mm).^2;
            %       d3poutdB3(nn)=d3poutdB3(nn)+ptemp*((B2b(nn)-BB1(mm)).^3./cc1(mm).^3-3*(B2b(nn)-BB1(mm))./cc1(mm))./cc1(mm).^3;
                
                %end
            end
            ExcessCDF=(Pout(nn)-PIn(nn))-ZProb(nn);
            %[dB] =SolveQuadraticRoot(ExcessCDF,pout,dpoutdB,DirectionFlag);
            %[dB] =SolveQuadraticRoot(ExcessCDF,pout(nn),dpoutdB(nn),+1);
       
            [dB] =SolveQuarticRootForProb(ExcessCDF,pout(nn),dpoutdB(nn),d2poutdB2(nn),d3poutdB3(nn),+1);
            dB=real(dB);
            B2a0=B2a(nn);
            B2b0=B2b(nn);
            B2b(nn)=B2b(nn)+dB;
            B2b1=B2b(nn);
            if(nn<Nn)
                B2a(nn+1)=B2b(nn);
            end
            Pout2(nn)=0.0;
            for mm=1:NN1
                %if(abs(B2b0-BB1(mm))<8*cc1(mm))
                   
                    [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
           %         if(nn<=171)
           %        [Pmn] = CalculateCDFFromSubDiv02(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),0);
           %         end
           %         if(nn>=172)
           %        [Pmn] = CalculateCDFFromSubDiv02(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),1);
           %         end
                   Pout2(nn)=Pout2(nn)+ Pmn; 
                   mm
                   Pmn
                %end
            end
            
            ExcessCDF2=(Pout2(nn)-PIn(nn))-ZProb(nn);
            TotalExcessCDF2=TotalExcessCDF2+ExcessCDF2;
            %PIn(nn)
            %Pout(nn)
            %out2(nn)
            ZProb(nn)
            ExcessCDF
            ExcessCDF2
            TotalExcessCDF2
            dB
            %B2b0
            %B2b1
            %B2a0
            nn
            

       % B2b    
       % nn    
       % dB
       % ZProb(nn)
       % ExcessCDF    
        str=input('Look nos-end');    
            
            
       end
       
       
       B2b(NnMidl)=0.0;
       for nn=NnMidl:-1:30
           
           
%             SigmaB(nn)=sqrt(dBdZ(nn).^2+ dw2(nn));
%             if(nn==NnMidh)
%                 B3(nn)=SigmaB(nn).*dNn/2;
%             else
%                 B3(nn)=B3(nn-1)+SigmaB(nn).*dNn;
%             end
%             
%             
%             B2(nn)=B2a(nn)+SigmaB(nn).*dNn/2;
%             
%             B2b(nn)=B2a(nn)+SigmaB(nn).*dNn;

           
           
            SigmaB(nn)=sqrt(dBdZ_0(nn).^2+ dw2(nn));
            if(nn==NnMidl)
                B3(nn)=-SigmaB(nn).*dNn/2;
            else
                B3(nn)=B3(nn+1)-SigmaB(nn).*dNn;
            end
            B2(nn)=B2b(nn)-SigmaB(nn).*dNn/2;
            B2a(nn)=B2b(nn)-SigmaB(nn).*dNn;
            PIn(nn)=0;
            Pout(nn)=0;
            pout(nn)=0;
            dpoutdB(nn)=0.0;
            d2poutdB2(nn)=0.0;
            d3poutdB3(nn)=0.0;
            pin(nn)=0;
            dpindB(nn)=0.0;
            d2pindB2(nn)=0.0;
            d3pindB3(nn)=0.0;
            for mm=1:NN1
                %if(abs(B2a(nn)-BB1(mm))<8*cc1(mm))
                    mm
                  cc1(mm);  
                  [Pmn] = CalculateCDFFromSubDiv(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));

                    
                    Pout(nn)=Pout(nn)+ Pmn;
                    %[Pmn,pmn,dpmn] = CalculateCDFAndDerivativesFromSubDiv(Bn,sigma0,Bm0,Bm1,Bm2,dPm,pm0,dpm0,d2pm0,d3pm0);
                   [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(B2a(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
 
                    
                   PIn(nn)=PIn(nn)+ Pmn;
                   
                   %ptemp=pmn;
                   pin(nn)=pin(nn)+pmn;
                   dpindB(nn)=dpindB(nn)+dpmn;
                   d2pindB2(nn)=d2pindB2(nn)+d2pmn;
                   d3pindB3(nn)=d3pindB3(nn)+d3pmn;
                   %d2poutdB2(nn)=d2poutdB2(nn)+d2pmn;
                   %d3poutdB3(nn)=d3poutdB3(nn)+ptemp*((B2a(nn)-BB1(mm)).^3./cc1(mm).^3-3*(B2a(nn)-BB1(mm))./cc1(mm))./cc1(mm).^3;    
             
                %end
            end
            %NN1
            
            ExcessCDF=(Pout(nn)-PIn(nn))-ZProb(nn);
            nn
            ZProb(nn)
            ExcessCDF
            pout(nn)
            dpoutdB(nn)
            %[dB] =SolveQuadraticRoot(ExcessCDF,pin(nn),dpindB(nn),-1);
            %dB
            
            [dB] =SolveQuarticRootForProb(ExcessCDF,pin(nn),dpindB(nn),d2pindB2(nn),d3pindB3(nn),-1);
            dB=real(dB);
            %str=input('Look at numbers in second part')
            B2a(nn)=B2a(nn)+dB;
            if(nn>1)
            B2b(nn-1)=B2a(nn);
            end

            
       end
       
       plot((1:Nn),SigmaB(1:Nn),'b');
       str=input('Look at SigmaB');
       
       
       
       [B2] = CalculateGridSubs(B2a,B2b,Z,wnStart,Nn,dNn);
       
       plot((1:Nn),B1(1:Nn),'r',(1:Nn),B2(1:Nn),'b',(1:Nn),B3(1:Nn),'k')
       str=input('Look at comparison of new and old Bs');
       
       
       w(wnStart:Nn)=wMid+wMu0dt(wnStart:Nn)+B2(wnStart:Nn);
       
       plot((1:Nn),w(1:Nn),'r')
       str=input('Calculated Value of w');
       
           
    end
end
    


%plot((1:Nn),ZProb(1:Nn),'g',(1:Nn),Pprev(1:Nn),'r');
%plot((1:Nn),ZProb(1:Nn),'g',(1:Nn),Pprev(1:Nn),'r');
%str=input('Look at distributions');

%Convert the expected values in each cell to standard Values associated with the grid cell after removing the
%integrated probability in the cell.
%w(wnStart:Nn)=Ewprev(wnStart:Nn)./Pprev(wnStart:Nn);
%w1(wnStart:Nn)=Ew1prev(wnStart:Nn)./Pprev(wnStart:Nn);
w1=w;
yy(wnStart:Nn)=((1-gamma)*w(wnStart:Nn)).^(1/(1-gamma));
yy1(wnStart:Nn)=((1-gamma)*w1(wnStart:Nn)).^(1/(1-gamma));


%below D's (the names of variables starting with D) are 
%change of probability derivatives.

y_w(1:Nn)=0;
y_w(wnStart:Nn) = ((1-gamma)*w(wnStart:Nn)).^(1/(1-gamma));
y_w1(1:Nn)=0;
y_w1(wnStart:Nn) = ((1-gamma)*w1(wnStart:Nn)).^(1/(1-gamma));
Dfy_w(wnStart:Nn)=0;
Dfy_w1(wnStart:Nn)=0;
for nn=wnStart+1:Nn-1
    Dfy_w(nn) = (y_w(nn + 1) - y_w(nn - 1))/(Z(nn + 1) - Z(nn - 1));
    Dfy_w1(nn) = (y_w1(nn + 1) - y_w1(nn - 1))/(Z(nn + 1) - Z(nn - 1));
    %Change of variable derivative for densities
end
py_w(1:Nn)=0;
py_w1(1:Nn)=0;
for nn = wnStart:Nn-1
    py_w(nn) = (normpdf(Z(nn),0, 1))/abs(Dfy_w(nn));%Origianl coordinates density
    py_w1(nn) = (normpdf(Z(nn),0, 1))/abs(Dfy_w1(nn));
end

toc

ItoHermiteMean=sum(y_w(wnStart+1:Nn-1).*ZProb(wnStart+1:Nn-1)) %Original process average from coordinates 
disp('true Mean only applicable to standard SV mean reverting type models otherwise disregard');
TrueMean=theta+(x0-theta)*exp(-kappa*dt*Tt)%Mean reverting SDE original variable true average

rng(29079137, 'twister')
paths=200000;
YY(1:paths)=x0;  %Original process monte carlo.
Random1(1:paths)=0;
for tt=1:TtM
    
    Random1=randn(size(Random1));
    HermiteP1(1,1:paths)=1;
    HermiteP1(2,1:paths)=Random1(1:paths);
    HermiteP1(3,1:paths)=Random1(1:paths).^2-1;
    HermiteP1(4,1:paths)=Random1(1:paths).^3-3*Random1(1:paths);
    HermiteP1(5,1:paths)=Random1(1:paths).^4-6*Random1(1:paths).^2+3;
    

    YY(1:paths)=YY(1:paths) + ...
        (YCoeff0(1,1,2,1).*YY(1:paths).^Fp(1,1,2,1)+ ...
        YCoeff0(1,2,1,1).*YY(1:paths).^Fp(1,2,1,1)+ ...
        YCoeff0(2,1,1,1).*YY(1:paths).^Fp(2,1,1,1))*dtM + ...
        (YCoeff0(1,1,3,1).*YY(1:paths).^Fp(1,1,3,1)+ ...
        YCoeff0(1,2,2,1).*YY(1:paths).^Fp(1,2,2,1)+ ...
        YCoeff0(2,1,2,1).*YY(1:paths).^Fp(2,1,2,1)+ ...
        YCoeff0(1,3,1,1).*YY(1:paths).^Fp(1,3,1,1)+ ...
        YCoeff0(2,2,1,1).*YY(1:paths).^Fp(2,2,1,1)+ ...
        YCoeff0(3,1,1,1).*YY(1:paths).^Fp(3,1,1,1))*dtM^2 + ...
        ((YCoeff0(1,1,1,2).*YY(1:paths).^Fp(1,1,1,2).*sqrt(dtM))+ ...
        (YCoeff0(1,1,2,2).*YY(1:paths).^Fp(1,1,2,2)+ ...
        YCoeff0(1,2,1,2).*YY(1:paths).^Fp(1,2,1,2)+ ...
        YCoeff0(2,1,1,2).*YY(1:paths).^Fp(2,1,1,2)).*dtM^1.5) .*HermiteP1(2,1:paths) + ...
        ((YCoeff0(1,1,1,3).*YY(1:paths).^Fp(1,1,1,3) *dtM) + ...
        (YCoeff0(1,1,2,3).*YY(1:paths).^Fp(1,1,2,3)+ ...
        YCoeff0(1,2,1,3).*YY(1:paths).^Fp(1,2,1,3)+ ...
        YCoeff0(2,1,1,3).*YY(1:paths).^Fp(2,1,1,3)).*dtM^2).*HermiteP1(3,1:paths) + ...
        ((YCoeff0(1,1,1,4).*YY(1:paths).^Fp(1,1,1,4)*dtM^1.5 )).*HermiteP1(4,1:paths) + ...
        (YCoeff0(1,1,1,5).*YY(1:paths).^Fp(1,1,1,5)*dtM^2.0).*HermiteP1(5,1:paths);
    

end

YY(YY<0)=0;
disp('Original process average from monte carlo');
MCMean=sum(YY(:))/paths %origianl coordinates monte carlo average.
MCVar=sum((YY(:)-MCMean).^2)/paths
disp('Original process average from our simulation');
ItoHermiteMean=sum(y_w(wnStart+1:Nn-1).*ZProb(wnStart+1:Nn-1)) %Original process average from coordinates 
ItoHermiteVar=sum((y_w(wnStart+1:Nn-1)-ItoHermiteMean).^2.*ZProb(wnStart+1:Nn-1)) 
disp('true Mean only applicble to standard SV mean reverting type models otherwise disregard');
TrueMean=theta+(x0-theta)*exp(-kappa*dt*Tt)%Mean reverting SDE original variable true average

MaxCutOff=30;
NoOfBins=round(300*gamma^2*4*sigma0/sqrt(MCMean)/(1+kappa));%Decrease the number of bins if the graph is too 
[YDensity,IndexOutY,IndexMaxY] = MakeDensityFromSimulation_Infiniti_NEW(YY,paths,NoOfBins,MaxCutOff );

%plot(y_w1(wnStart+1:Nn-1),py_w1(wnStart+1:Nn-1),'b',y_w(wnStart+1:Nn-1),py_w(wnStart+1:Nn-1),'r',IndexOutY(1:IndexMaxY),YDensity(1:IndexMaxY),'g');
%plot(y_w(wnStart+1:Nn-1),py_w(wnStart+1:Nn-1),'r',IndexOutY(1:IndexMaxY),YDensity(1:IndexMaxY),'g');
plot(y_w(wnStart+1:Nn-1),py_w(wnStart+1:Nn-1),'r',y_w1(wnStart+1:Nn-1),py_w1(wnStart+1:Nn-1),'b',IndexOutY(1:IndexMaxY),YDensity(1:IndexMaxY),'g');

title(sprintf('x0 = %.4f,theta=%.3f,kappa=%.2f,gamma=%.3f,sigma=%.2f,T=%.2f,dt=%.5f,M=%.4f,TM=%.4f', x0,theta,kappa,gamma,sigma0,T,dt,ItoHermiteMean,TrueMean));%,sprintf('theta= %f', theta), sprintf('kappa = %f', kappa),sprintf('sigma = %f', sigma0),sprintf('T = %f', T));
 
legend({'Improvised terms Model Density','Monte Carlo Density'},'Location','northeast')
 
str=input('red line is density of SDE from Ito-Hermite method, green is monte carlo.');
end
.
This function is associated with very simple root selection algorithm.
.
function [dB] =SolveQuarticRootForProb(ExcessCDF,pout,dpoutdB,d2poutdB2,d3poutdB3,DirectionFlag)
%ChooseQuadraticRoot(dB1,dB2,ExcessCDF,pout(nn),dpoutdB(nn),DirectionFlag)
             
if(DirectionFlag==1)
    if(ExcessCDF>0)

        a0=1/24*d3poutdB3;
        b0=1/6*d2poutdB2;
        c0=1/2*dpoutdB;
        d0=pout;
        e0=ExcessCDF;
        
        [dB1,dB2,dB3,dB4] =SolveQuarticRootMathematica(a0,b0,c0,d0,e0);

        dB0=-ExcessCDF/pout;
        dB1
        dB2
        dB3
        dB4
        dB0
        
        a0*dB1^4+b0*dB1^3+c0*dB1^2+d0*dB1+e0
        a0*dB2^4+b0*dB2^3+c0*dB2^2+d0*dB2+e0
        a0*dB3^4+b0*dB3^3+c0*dB3^2+d0*dB3+e0
        a0*dB4^4+b0*dB4^3+c0*dB4^2+d0*dB4+e0
        
        
        Bdiff=10000;
        if(dB1<0)
            Bdiff=abs(dB1-dB0);
            dB=dB1;
        end
        if((dB2<0)&&(abs(dB2-dB0)<Bdiff))
            Bdiff=abs(dB2-dB0);
            dB=dB2;
        end
        if((dB3<0)&&(abs(dB3-dB0)<Bdiff))
            Bdiff=abs(dB3-dB0);
            dB=dB3;
        end
        if((dB4<0)&&(abs(dB4-dB0)<Bdiff))
            Bdiff=abs(dB4-dB0);
            dB=dB4;
        end

    elseif(ExcessCDF<0)
        
        a0=1/24*d3poutdB3;
        b0=1/6*d2poutdB2;
        c0=1/2*dpoutdB;
        d0=pout;
        e0=ExcessCDF;
        
        [dB1,dB2,dB3,dB4] =SolveQuarticRootMathematica(a0,b0,c0,d0,e0);

        dB0=-ExcessCDF/pout;

        dB1
        dB2
        dB3
        dB4
        dB0
        
        a0*dB1^4+b0*dB1^3+c0*dB1^2+d0*dB1+e0
        a0*dB2^4+b0*dB2^3+c0*dB2^2+d0*dB2+e0
        a0*dB3^4+b0*dB3^3+c0*dB3^2+d0*dB3+e0
        a0*dB4^4+b0*dB4^3+c0*dB4^2+d0*dB4+e0
        
        
        
        Bdiff=10000;
        if(dB1>0)
            Bdiff=abs(dB1-dB0);
            dB=dB1;
        end
        if((dB2>0)&&(abs(dB2-dB0)<Bdiff))
            Bdiff=abs(dB2-dB0);
            dB=dB2;
        end
        if((dB3>0)&&(abs(dB3-dB0)<Bdiff))
            Bdiff=abs(dB3-dB0);
            dB=dB3;
        end
        if((dB4>0)&&(abs(dB4-dB0)<Bdiff))
            Bdiff=abs(dB4-dB0);
            dB=dB4;
        end
    end
end
if(DirectionFlag==-1)
    if(ExcessCDF>0)

        %a0=1/2*dpoutdB;
        %b0=pout;
        %c0=-ExcessCDF;

        a0=1/24*d3poutdB3;
        b0=1/6*d2poutdB2;
        c0=1/2*dpoutdB;
        d0=pout;
        e0=-ExcessCDF;
        
        [dB1,dB2,dB3,dB4] =SolveQuarticRootMathematica(a0,b0,c0,d0,e0);

        dB0=ExcessCDF/pout;
        
                dB1
        dB2
        dB3
        dB4
        dB0
        
        a0*dB1^4+b0*dB1^3+c0*dB1^2+d0*dB1+e0
        a0*dB2^4+b0*dB2^3+c0*dB2^2+d0*dB2+e0
        a0*dB3^4+b0*dB3^3+c0*dB3^2+d0*dB3+e0
        a0*dB4^4+b0*dB4^3+c0*dB4^2+d0*dB4+e0

        
        Bdiff=10000;
        if(dB1>0)
            Bdiff=abs(dB1-dB0);
            dB=dB1;
        end
        if((dB2>0)&&(abs(dB2-dB0)<Bdiff))
            Bdiff=abs(dB2-dB0);
            dB=dB2;
        end
        if((dB3>0)&&(abs(dB3-dB0)<Bdiff))
            Bdiff=abs(dB3-dB0);
            dB=dB3;
        end
        if((dB4>0)&&(abs(dB4-dB0)<Bdiff))
            Bdiff=abs(dB4-dB0);
            dB=dB4;
        end
    elseif(ExcessCDF<0)

    %    a0=1/2*dpoutdB;
    %    b0=-pout;
    %    c0=ExcessCDF;
        
        
        a0=1/24*d3poutdB3;
        b0=1/6*d2poutdB2;
        c0=1/2*dpoutdB;
        d0=pout;
        e0=-ExcessCDF;
        
        [dB1,dB2,dB3,dB4] =SolveQuarticRootMathematica(a0,b0,c0,d0,e0);
    
        dB0=ExcessCDF/pout
        

        Bdiff=10000;
        if(dB1<0)
            Bdiff=abs(dB1-dB0);
            dB=dB1;
        end
        if((dB2<0)&&(abs(dB2-dB0)<Bdiff))
            Bdiff=abs(dB2-dB0);
            dB=dB2;
        end
        if((dB3<0)&&(abs(dB3-dB0)<Bdiff))
            Bdiff=abs(dB3-dB0);
            dB=dB3;
        end
        if((dB4<0)&&(abs(dB4-dB0)<Bdiff))
            Bdiff=abs(dB4-dB0);
            dB=dB4;
        end
    end
end

.
.
First 4 derivatives function.
.
function [dwdZ,d2wdZ2,d3wdZ3,d4wdZ4] = First4Derivatives2ndOrderEqSpaced(wnStart,Nn,dNn,w,Z)


  d4wdZ4(wnStart)=(3*w(wnStart)-14*w(wnStart+1)+26*w(wnStart+2)-24*w(wnStart+3)+11*w(wnStart+4)-2*w(wnStart+5))/(dNn.^4);
  d4wdZ4(wnStart+1)=(2*w(wnStart)-9*w(wnStart+1)+16*w(wnStart+2)-14*w(wnStart+3)+6*w(wnStart+4)-1*w(wnStart+5))/(dNn.^4);
  d4wdZ4(wnStart+2:Nn-2)=(1*w(wnStart:Nn-4)-4*w(wnStart+1:Nn-3)+6*w(wnStart+2:Nn-2)-4*w(wnStart+3:Nn-1)+1*w(wnStart+4:Nn))/(dNn.^4);
  d4wdZ4(Nn-1)=(2*w(Nn)-9*w(Nn-1)+16*w(Nn-2)-14*w(Nn-3)+6*w(Nn-4)-1*w(Nn-5))/(dNn.^4);
  d4wdZ4(Nn)=(3*w(Nn)-14*w(Nn-1)+26*w(Nn-2)-24*w(Nn-3)+11*w(Nn-4)-2*w(Nn-5))/(dNn.^4);
  
  d3wdZ3(wnStart)=(-5*w(wnStart)+18*w(wnStart+1)-24*w(wnStart+2)+14*w(wnStart+3)-3*w(wnStart+4))/(2*dNn.^3);
  d3wdZ3(wnStart+1)=(-3*w(wnStart)+10*w(wnStart+1)-12*w(wnStart+2)+6*w(wnStart+3)-1*w(wnStart+4))/(2*dNn.^3);
  d3wdZ3(wnStart+2:Nn-2)=(-1*w(wnStart:Nn-4)+2*w(wnStart+1:Nn-3)+0*w(wnStart+2:Nn-2)-2*w(wnStart+3:Nn-1)+1*w(wnStart+4:Nn))/(2*dNn.^3);
  d3wdZ3(Nn-1)=(3*w(Nn)-10*w(Nn-1)+12*w(Nn-2)-6*w(Nn-3)+1*w(Nn-4))/(2*dNn.^3);
  d3wdZ3(Nn)=(5*w(Nn)-18*w(Nn-1)+24*w(Nn-2)-14*w(Nn-3)+3*w(Nn-4))/(2*dNn.^3);

%d4wdZ4(wnStart:Nn)=0;
%d3wdZ3(wnStart:Nn)=0;
 
 [wS] = InterpolateOrderN6(5,Z(wnStart)-dNn,Z(wnStart),Z(wnStart+1),Z(wnStart+2),Z(wnStart+3),Z(wnStart+4),Z(wnStart+5),w(wnStart),w(wnStart+1),w(wnStart+2),w(wnStart+3),w(wnStart+4),w(wnStart+5));
 [wE] = InterpolateOrderN6(5,Z(Nn)+dNn,Z(Nn),Z(Nn-1),Z(Nn-2),Z(Nn-3),Z(Nn-4),Z(Nn-5),w(Nn),w(Nn-1),w(Nn-2),w(Nn-3),w(Nn-4),w(Nn-5));

 
 d2wdZ2(wnStart)=(wS-2*w(wnStart)+w(wnStart+1))/(dNn.^2);
 d2wdZ2(wnStart+1:Nn-1)=(w(wnStart:Nn-2)-2*w(wnStart+1:Nn-1)+1*w(wnStart+2:Nn))/(dNn.^2);
 d2wdZ2(Nn)=(wE-2*w(Nn)+w(Nn-1))/(dNn.^2);
 
 
 dwdZ(wnStart)=(-1*wS+1*w(wnStart+1))/(2*dNn);
 dwdZ(wnStart+1:Nn-1)=(-1*w(wnStart:Nn-2)+1*w(wnStart+2:Nn))/(2*dNn);
 dwdZ(Nn)=(wE-w(Nn-1))/(2*dNn);
 
 
 %dwdZ(wnStart)=(-3*w(wnStart)+4*w(wnStart+1)-1*w(wnStart+2))/(2*dNn);
 %dwdZ(wnStart+1:Nn-1)=(-1*w(wnStart:Nn-2)+1*w(wnStart+2:Nn))/(2*dNn);
 %dwdZ(Nn)=(3*w(Nn)-4*w(Nn-1)+1*w(Nn-2))/(2*dNn);
 
end
.
Another function.
.
function [B] = CalculateGridSubs(Ba,Bb,Z,wnStart,Nn,dNn)
%UNTITLED4 Summary of this function goes here
%   Detailed explanation goes here


Za(wnStart:Nn)=Z(wnStart:Nn)-.5*dNn;
Zb(wnStart:Nn)=Z(wnStart:Nn)+.5*dNn;

for nn=wnStart+2:Nn-2
    x0a(nn-wnStart-2+1)=Z(nn);
    
    x1(nn-wnStart-2+1)=Za(nn-2);
    x2(nn-wnStart-2+1)=Za(nn-1);
    x3(nn-wnStart-2+1)=Za(nn);
    x4(nn-wnStart-2+1)=Zb(nn);
    x5(nn-wnStart-2+1)=Zb(nn+1);
    x6(nn-wnStart-2+1)=Zb(nn+2);
    

    y1(nn-wnStart-2+1)=Ba(nn-2);
    y2(nn-wnStart-2+1)=Ba(nn-1);
    y3(nn-wnStart-2+1)=Ba(nn);
    y4(nn-wnStart-2+1)=Bb(nn);
    y5(nn-wnStart-2+1)=Bb(nn+1);
    y6(nn-wnStart-2+1)=Bb(nn+2);
    
end

N=6;
    [y0a] = InterpolateOrderN6(N,x0a,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);
    B(wnStart+2:Nn-2)=y0a(1:Nn-2-wnStart-2+1);
    
    
    
    
    x01=Z(wnStart+1);
    x02=Z(wnStart);
    
    x1=Za(wnStart);
    x2=Za(wnStart+1);
    x3=Zb(wnStart+1);
    x4=Zb(wnStart+2);
    x5=Zb(wnStart+3);
    x6=0;
    
    y1=Ba(wnStart);
    y2=Ba(wnStart+1);
    y3=Bb(wnStart+1);
    y4=Bb(wnStart+2);
    y5=Bb(wnStart+3);
    y6=0;
    N=5;
    [y01] = InterpolateOrderN6(N,x01,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);

    B(wnStart+1)=y01;
    
    [y02] = InterpolateOrderN6(N,x02,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);

    B(wnStart)=y02;
    
    

    x01=Z(Nn-1);
    x02=Z(Nn);
    
    x1=Za(Nn-3);
    x2=Za(Nn-2);
    x3=Za(Nn-1);
    x4=Za(Nn);
    x5=Zb(Nn);
    x6=0;
    

    y1=Ba(Nn-3);
    y2=Ba(Nn-2);
    y3=Ba(Nn-1);
    y4=Ba(Nn);
    y5=Bb(Nn);
    y6=0;
    N=5;
    [y01] = InterpolateOrderN6(N,x01,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);
    [y02] = InterpolateOrderN6(N,x02,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);
    


    B(Nn-1)=y01;
    B(Nn)=y02;
    
    end

.
.
function [Pmn] = CalculateCDFFromSubDiv(Bn,sigma0,Bm0,Bm1,Bm2,dPm,pm0,dpm0,d2pm0,d3pm0,d4pm0,d5pm0)

%function [Pmn,pmn,dpmn] = CalculateCDFAndDerivativesFromSubDiv(Bn,sigma0,Bm0,Bm1,Bm2,Zm,dNn,dPm,Pm0,pm0,dpm0,d2pm0,d3pm0,dZdBm0,d2ZdB2m0,d3ZdB3m0)
 
%sort out B2a and B2b below.
%sigma0=cc1;
Bt=Bn-Bm0;
Zt=(Bn-Bm0)/sigma0;
Zt2=Zt^2;
Zt3=Zt^3;
Zt4=Zt^4;
cc1=sigma0;
cc2=sigma0^2;
cc3=sigma0^3;
cc4=sigma0^4;

Bn
Bm0
Bt

Pm0n=normcdf(Bt,0,cc1)
pm0n=normpdf(Bt,0,cc1)
dpm0n=-pm0n*(Zt)./cc1;
d2pm0n=pm0n*(Zt2-1)./cc2;
d3pm0n=-pm0n*(Zt3-3*Zt)./cc3;
d4pm0n=pm0n*(Zt4-6*Zt2+3)./cc4;

% Zmpdf=normpdf(Zm,0,1);
% pm0=Zmpdf.*dZdBm;
% dpm0=-Zm.*Zmpdf.*dZdBm.^2+Zmpdf.*d2ZdB2m;
% d2pm0=(Zm.^2-1).*Zmpdf.*dZdBm.^3+3*(-Zm).*Zmpdf.*dZdBm.*d2ZdB2m+Zmpdf.*d3ZdB3m;
% d3pm0=(-1)*(Zm.^3-3*Zm).*Zmpdf.*dZdBm.^4+6*(Zm.^2-1).*Zmpdf.*dZdBm.^2.*d2ZdB2m + ...
%     4*-Zm.*Zmpdf.*dZdBm.*d3ZdB3m + 3*-Zm.*Zmpdf.*d2ZdB2m.^2+ Zmpdf.*d4ZdB4m;

Zm1=Bn-(Bm1);
Zm2=Bn-(Bm2);



dBm=Bm2-Bm1;
dBm2=1/3* ((Bm2 - Bm0)^3 - (Bm1 - Bm0)^3)/2;
dBm3=1/4* ((Bm2 - Bm0)^4 - (Bm1 - Bm0)^4)/6;
dBm4=1/5* ((Bm2 - Bm0)^5 - (Bm1 - Bm0)^5)/24;
dBm5=1/6* ((Bm2 - Bm0)^6 - (Bm1 - Bm0)^6)/120;
dBm6=1/7* ((Bm2 - Bm0)^7 - (Bm1 - Bm0)^7)/720;

%IntegralCDF=Integral0+  pm0.*(+Integral21+Integral22+Integral1)-  Pm0n*pm0*dBm + 2* dpm0 * pm0n *dBm2 + ...
%    + (3*d2pm0*pm0n + 3*dpm0*dpm0n)*dBm3 + ...
%    + (4*d3pm0*pm0n + 6* d2pm0*dpm0n + 4* dpm0 * d2pm0n)*dBm4 + ...
%    + (5*d4pm0*dpm0n + 10* d3pm0*dpm0n+ 10* d2pm0*d2pm0n + 5* dpm0 * d3pm0n)*dBm5 + ...
%    + (6*d5pm0*dpm0n + 15* d4pm0*dpm0n+ 20* d3pm0*d2pm0n + 15* d2pm0 * d3pm0n+ 6* dpm0 * d4pm0n) * dBm6;

%Pmn=IntegralCDF;

Bt=Bn-Bm0;
Zt=(Bn-Bm0)/sigma0;
Zt2=Zt^2;
Zt3=Zt^3;
Zt4=Zt^4;
Zt5=Zt^5;
Zt6=Zt^6;
Zt7=Zt^7;
Zt8=Zt^8;
cc1=sigma0;
cc2=sigma0^2;
cc3=sigma0^3;
cc4=sigma0^4;
cc5=sigma0^5;
cc6=sigma0^6;
cc7=sigma0^7;
cc8=sigma0^8;

Integral21=(0.398942* exp(-((0.5* Zm1^2)/sigma0^2)) - 0.398942* exp(-((0.5* Zm2^2)/sigma0^2)))*sigma0;
Integral22=-Bn*(normcdf(Zm2,0,sigma0)-normcdf(Zm1,0,sigma0));
Integral1=Bm2*normcdf(Zm2,0,sigma0)-Bm1*normcdf(Zm1,0,sigma0);
Integral0=dPm.*Pm0n;



Pm0n=normcdf(Bt,0,cc1);
pm0n=normpdf(Bt,0,cc1);
dPm0ndZt=normpdf(Bt,0,cc1);
d2Pm0ndZt2=-pm0n*(Zt)./cc1;
d3Pm0ndZt3=pm0n*(Zt2-1)./cc2;
d4Pm0ndZt4=-pm0n*(Zt3-3*Zt)./cc3;
d5Pm0ndZt5=pm0n*(Zt4-6*Zt2+3)./cc4;
d6Pm0ndZt6=-pm0n*(Zt5-10*Zt3+15*Zt)./cc5;
d7Pm0ndZt7=pm0n*(Zt6-15*Zt4+45*Zt2-15)./cc6;
d8Pm0ndZt8=-pm0n*(Zt7-21*Zt5+105*Zt3-105*Zt)/cc7;                      
d9Pm0ndZt9=pm0n*(Zt8-28*Zt6+210*Zt4-420*Zt2+105)./cc8;

dBmdZt=-1;

IntegralCDF=Integral0+  pm0.*(+Integral21+Integral22+Integral1)-  Pm0n*pm0*dBm + 2* dpm0 * (dPm0ndZt*dBmdZt) *dBm2 + ...
    + (3*d2pm0*(dPm0ndZt*dBmdZt) + 3*dpm0*(d2Pm0ndZt2*dBmdZt^2))*dBm3 + ...
    + (4*d3pm0*(dPm0ndZt*dBmdZt) + 6* d2pm0*(d2Pm0ndZt2*dBmdZt^2) + 4* dpm0 * (d3Pm0ndZt3*dBmdZt^3))*dBm4 + ...
    + (5*d4pm0*(dPm0ndZt*dBmdZt) + 10* d3pm0*(d2Pm0ndZt2*dBmdZt^2)+ 10* d2pm0*(d3Pm0ndZt3*dBmdZt^3) + 5* dpm0 * (d4Pm0ndZt4*dBmdZt^4))*dBm5 + ...
    + (6*d5pm0*(dPm0ndZt*dBmdZt) + 15* d4pm0*(d2Pm0ndZt2*dBmdZt^2)+ 20* d3pm0*(d3Pm0ndZt3*dBmdZt^3) + 15* d2pm0 * (d4Pm0ndZt4*dBmdZt^4)+ ...
    6* dpm0 * (d5Pm0ndZt5*dBmdZt^5)) * dBm6;


Pmn=IntegralCDF;



end
.
.
function [GridStarts,GridEnds] = CalculateGridStartsAndEndsBoundedEnds(w,Z,wnStart,Nn,dNn)
%UNTITLED4 Summary of this function goes here
%   Detailed explanation goes here



for nn=wnStart+2:Nn-3
    x0(nn-wnStart-2+1)=Z(nn)+.5*dNn;
    x1(nn-wnStart-2+1)=Z(nn-2);
    x2(nn-wnStart-2+1)=Z(nn-1);
    x3(nn-wnStart-2+1)=Z(nn);
    x4(nn-wnStart-2+1)=Z(nn+1);
    x5(nn-wnStart-2+1)=Z(nn+2);
    x6(nn-wnStart-2+1)=Z(nn+3);

    y1(nn-wnStart-2+1)=w(nn-2);
    y2(nn-wnStart-2+1)=w(nn-1);
    y3(nn-wnStart-2+1)=w(nn);
    y4(nn-wnStart-2+1)=w(nn+1);
    y5(nn-wnStart-2+1)=w(nn+2);
    y6(nn-wnStart-2+1)=w(nn+3);
end

N=6;
    [y0] = InterpolateOrderN6(N,x0,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);
    GridEnds(wnStart+2:Nn-3)=y0(1:Nn-3-wnStart-2+1);
    
    
    x0=Z(wnStart+1)+.5*dNn;
    x1=Z(wnStart);
    x2=Z(wnStart+1);
    x3=Z(wnStart+2);
    x4=Z(wnStart+3);
    x5=Z(wnStart+4);
    x6=0;
    

    y1=w(wnStart);
    y2=w(wnStart+1);
    y3=w(wnStart+2);
    y4=w(wnStart+3);
    y5=w(wnStart+4);
    y6=0;
    N=5;
    [y0] = InterpolateOrderN6(N,x0,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);

    GridEnds(wnStart+1)=y0;
    
    x01=Z(wnStart)+.5*dNn;
    x02=Z(wnStart)-.5*dNn;
    x1=Z(wnStart);
    x2=Z(wnStart+1);
    x3=Z(wnStart+2);
    x4=Z(wnStart+3);
    
 

    y1=w(wnStart);
    y2=w(wnStart+1);
    y3=w(wnStart+2);
    y4=w(wnStart+3);
    
    
    N=4;
    [y01] = InterpolateOrderN6(N,x01,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);
    [y02] = InterpolateOrderN6(N,x02,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);
    GridEnds(wnStart)=y01;
    GridStarts(wnStart)=y02;


    x0=Z(Nn-2)+.5*dNn;
    x1=Z(Nn-4);
    x2=Z(Nn-3);
    x3=Z(Nn-2);
    x4=Z(Nn-1);
    x5=Z(Nn);
    x6=0;
    

    y1=w(Nn-4);
    y2=w(Nn-3);
    y3=w(Nn-2);
    y4=w(Nn-1);
    y5=w(Nn);
    y6=0;
    N=5;
    [y0] = InterpolateOrderN6(N,x0,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);

    GridEnds(Nn-2)=y0;
    
    x01=Z(Nn-1)+.5*dNn;
    x02=Z(Nn)+.5*dNn;
    x1=Z(Nn-3);
    x2=Z(Nn-2);
    x3=Z(Nn-1);
    x4=Z(Nn);
    x5=0;
    x6=0;
    

   y1=w(Nn-3);
    y2=w(Nn-2);
    y3=w(Nn-1);
    y4=w(Nn);
    y5=0;
    y6=0;
    N=4;
    [y01] = InterpolateOrderN6(N,x01,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);
    [y02] = InterpolateOrderN6(N,x02,x1,x2,x3,x4,x5,x6,y1,y2,y3,y4,y5,y6);

    GridEnds(Nn-1)=y01;
    GridEnds(Nn)=y02;
    
    %GridEnds(Nn)=Inf;
    %GridStarts(wnStart)=-Inf;
    GridStarts(2:Nn)=GridEnds(1:Nn-1);
    
    end
.
.
function [y0] = InterpolateOrderN10(N,x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10)

if(N==10)
y0=(x0-x2).*(x0-x3).*(x0-x4).*(x0-x5).*(x0-x6).*(x0-x7).*(x0-x8).*(x0-x9).*(x0-x10)./((x1-x2).*(x1-x3).*(x1-x4).*(x1-x5).*(x1-x6).*(x1-x7).*(x1-x8).*(x1-x9).*(x1-x10)).*y1+ ...
   (x0-x1).*(x0-x3).*(x0-x4).*(x0-x5).*(x0-x6).*(x0-x7).*(x0-x8).*(x0-x9).*(x0-x10)./((x2-x1).*(x2-x3).*(x2-x4).*(x2-x5).*(x2-x6).*(x2-x7).*(x2-x8).*(x2-x9).*(x2-x10)).*y2+ ...
   (x0-x1).*(x0-x2).*(x0-x4).*(x0-x5).*(x0-x6).*(x0-x7).*(x0-x8).*(x0-x9).*(x0-x10)./((x3-x1).*(x3-x2).*(x3-x4).*(x3-x5).*(x3-x6).*(x3-x7).*(x3-x8).*(x3-x9).*(x3-x10)).*y3+ ...
   (x0-x1).*(x0-x2).*(x0-x3).*(x0-x5).*(x0-x6).*(x0-x7).*(x0-x8).*(x0-x9).*(x0-x10)./((x4-x1).*(x4-x2).*(x4-x3).*(x4-x5).*(x4-x6).*(x4-x7).*(x4-x8).*(x4-x9).*(x4-x10)).*y4+ ...
   (x0-x1).*(x0-x2).*(x0-x3).*(x0-x4).*(x0-x6).*(x0-x7).*(x0-x8).*(x0-x9).*(x0-x10)./((x5-x1).*(x5-x2).*(x5-x3).*(x5-x4).*(x5-x6).*(x5-x7).*(x5-x8).*(x5-x9).*(x5-x10)).*y5+ ...
   (x0-x1).*(x0-x2).*(x0-x3).*(x0-x4).*(x0-x5).*(x0-x7).*(x0-x8).*(x0-x9).*(x0-x10)./((x6-x1).*(x6-x2).*(x6-x3).*(x6-x4).*(x6-x5).*(x6-x7).*(x6-x8).*(x6-x9).*(x6-x10)).*y6+ ...
   (x0-x1).*(x0-x2).*(x0-x3).*(x0-x4).*(x0-x5).*(x0-x6).*(x0-x8).*(x0-x9).*(x0-x10)./((x7-x1).*(x7-x2).*(x7-x3).*(x7-x4).*(x7-x5).*(x7-x6).*(x7-x8).*(x7-x9).*(x7-x10)).*y7+ ...
   (x0-x1).*(x0-x2).*(x0-x3).*(x0-x4).*(x0-x5).*(x0-x6).*(x0-x7).*(x0-x9).*(x0-x10)./((x8-x1).*(x8-x2).*(x8-x3).*(x8-x4).*(x8-x5).*(x8-x6).*(x8-x7).*(x8-x9).*(x8-x10)).*y8+ ...
   (x0-x1).*(x0-x2).*(x0-x3).*(x0-x4).*(x0-x5).*(x0-x6).*(x0-x7).*(x0-x8).*(x0-x10)./((x9-x1).*(x9-x2).*(x9-x3).*(x9-x4).*(x9-x5).*(x9-x6).*(x9-x7).*(x9-x8).*(x9-x10)).*y9+ ...
   (x0-x1).*(x0-x2).*(x0-x3).*(x0-x4).*(x0-x5).*(x0-x6).*(x0-x7).*(x0-x8).*(x0-x9)./((x10-x1).*(x10-x2).*(x10-x3).*(x10-x4).*(x10-x5).*(x10-x6).*(x10-x7).*(x10-x8).*(x10-x9)).*y10;
   
end
if(N==9)
y0=(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)*(x0-x8)*(x0-x9)/((x1-x2).*(x1-x3).*(x1-x4).*(x1-x5).*(x1-x6).*(x1-x7).*(x1-x8).*(x1-x9))*y1+ ...
   (x0-x1)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)*(x0-x8)*(x0-x9)/((x2-x1).*(x2-x3).*(x2-x4).*(x2-x5).*(x2-x6).*(x2-x7).*(x2-x8).*(x2-x9))*y2+ ...
   (x0-x1)*(x0-x2)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)*(x0-x8)*(x0-x9)/((x3-x1).*(x3-x2).*(x3-x4).*(x3-x5).*(x3-x6).*(x3-x7).*(x3-x8).*(x3-x9))*y3+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x5)*(x0-x6)*(x0-x7)*(x0-x8)*(x0-x9)/((x4-x1).*(x4-x2).*(x4-x3).*(x4-x5).*(x4-x6).*(x4-x7).*(x4-x8).*(x4-x9))*y4+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x6)*(x0-x7)*(x0-x8)*(x0-x9)/((x5-x1).*(x5-x2).*(x5-x3).*(x5-x4).*(x5-x6).*(x5-x7).*(x5-x8).*(x5-x9))*y5+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x7)*(x0-x8)*(x0-x9)/((x6-x1).*(x6-x2).*(x6-x3).*(x6-x4).*(x6-x5).*(x6-x7).*(x6-x8).*(x6-x9))*y6+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x8)*(x0-x9)/((x7-x1).*(x7-x2).*(x7-x3).*(x7-x4).*(x7-x5).*(x7-x6).*(x7-x8).*(x7-x9))*y7+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)*(x0-x9)/((x8-x1).*(x8-x2).*(x8-x3).*(x8-x4).*(x8-x5).*(x8-x6).*(x8-x7).*(x8-x9))*y8+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)*(x0-x8)/((x9-x1).*(x9-x2).*(x9-x3).*(x9-x4).*(x9-x5).*(x9-x6).*(x9-x7).*(x9-x8))*y9;
end

if(N==8)
y0=(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)*(x0-x8)/((x1-x2).*(x1-x3).*(x1-x4).*(x1-x5).*(x1-x6).*(x1-x7).*(x1-x8))*y1+ ...
   (x0-x1)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)*(x0-x8)/((x2-x1).*(x2-x3).*(x2-x4).*(x2-x5).*(x2-x6).*(x2-x7).*(x2-x8))*y2+ ...
   (x0-x1)*(x0-x2)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)*(x0-x8)/((x3-x1).*(x3-x2).*(x3-x4).*(x3-x5).*(x3-x6).*(x3-x7).*(x3-x8))*y3+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x5)*(x0-x6)*(x0-x7)*(x0-x8)/((x4-x1).*(x4-x2).*(x4-x3).*(x4-x5).*(x4-x6).*(x4-x7).*(x4-x8))*y4+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x6)*(x0-x7)*(x0-x8)/((x5-x1).*(x5-x2).*(x5-x3).*(x5-x4).*(x5-x6).*(x5-x7).*(x5-x8))*y5+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x7)*(x0-x8)/((x6-x1).*(x6-x2).*(x6-x3).*(x6-x4).*(x6-x5).*(x6-x7).*(x6-x8))*y6+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x8)/((x7-x1).*(x7-x2).*(x7-x3).*(x7-x4).*(x7-x5).*(x7-x6).*(x7-x8))*y7+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)/((x8-x1).*(x8-x2).*(x8-x3).*(x8-x4).*(x8-x5).*(x8-x6).*(x8-x7))*y8;
   
end



if(N==7)
y0=(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)/((x1-x2).*(x1-x3).*(x1-x4).*(x1-x5).*(x1-x6).*(x1-x7))*y1+ ...
   (x0-x1)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)/((x2-x1).*(x2-x3).*(x2-x4).*(x2-x5).*(x2-x6).*(x2-x7))*y2+ ...
   (x0-x1)*(x0-x2)*(x0-x4)*(x0-x5)*(x0-x6)*(x0-x7)/((x3-x1).*(x3-x2).*(x3-x4).*(x3-x5).*(x3-x6).*(x3-x7))*y3+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x5)*(x0-x6)*(x0-x7)/((x4-x1).*(x4-x2).*(x4-x3).*(x4-x5).*(x4-x6).*(x4-x7))*y4+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x6)*(x0-x7)/((x5-x1).*(x5-x2).*(x5-x3).*(x5-x4).*(x5-x6).*(x5-x7))*y5+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x7)/((x6-x1).*(x6-x2).*(x6-x3).*(x6-x4).*(x6-x5).*(x6-x7))*y6+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)/((x7-x1).*(x7-x2).*(x7-x3).*(x7-x4).*(x7-x5).*(x7-x6))*y7;
end
if(N==6)
y0=(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)/((x1-x2).*(x1-x3).*(x1-x4).*(x1-x5).*(x1-x6))*y1+ ...
   (x0-x1)*(x0-x3)*(x0-x4)*(x0-x5)*(x0-x6)/((x2-x1).*(x2-x3).*(x2-x4).*(x2-x5).*(x2-x6))*y2+ ...
   (x0-x1)*(x0-x2)*(x0-x4)*(x0-x5)*(x0-x6)/((x3-x1).*(x3-x2).*(x3-x4).*(x3-x5).*(x3-x6))*y3+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x5)*(x0-x6)/((x4-x1).*(x4-x2).*(x4-x3).*(x4-x5).*(x4-x6))*y4+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x6)/((x5-x1).*(x5-x2).*(x5-x3).*(x5-x4).*(x5-x6))*y5+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)/((x6-x1).*(x6-x2).*(x6-x3).*(x6-x4).*(x6-x5))*y6;
end

if(N==5)
y0=(x0-x2)*(x0-x3)*(x0-x4)*(x0-x5)/((x1-x2).*(x1-x3).*(x1-x4).*(x1-x5))*y1+ ...
   (x0-x1)*(x0-x3)*(x0-x4)*(x0-x5)/((x2-x1).*(x2-x3).*(x2-x4).*(x2-x5))*y2+ ...
   (x0-x1)*(x0-x2)*(x0-x4)*(x0-x5)/((x3-x1).*(x3-x2).*(x3-x4).*(x3-x5))*y3+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x5)/((x4-x1).*(x4-x2).*(x4-x3).*(x4-x5))*y4+ ...
   (x0-x1)*(x0-x2)*(x0-x3)*(x0-x4)/((x5-x1).*(x5-x2).*(x5-x3).*(x5-x4))*y5;
end

if(N==4)
y0=(x0-x2)*(x0-x3)*(x0-x4)/((x1-x2).*(x1-x3).*(x1-x4))*y1+ ...
   (x0-x1)*(x0-x3)*(x0-x4)/((x2-x1).*(x2-x3).*(x2-x4))*y2+ ...
   (x0-x1)*(x0-x2)*(x0-x4)/((x3-x1).*(x3-x2).*(x3-x4))*y3+ ...
   (x0-x1)*(x0-x2)*(x0-x3)/((x4-x1).*(x4-x2).*(x4-x3))*y4;
end
if(N==3)
y0=(x0-x2)*(x0-x3)/((x1-x2).*(x1-x3))*y1+ ...
   (x0-x1)*(x0-x3)/((x2-x1).*(x2-x3))*y2+ ...
   (x0-x1)*(x0-x2)/((x3-x1).*(x3-x2))*y3;
end
if(N==2)
y0=(x0-x2)/((x1-x2))*y1+ ...
   (x0-x1)/((x2-x1))*y2;
end

%y0=(x0-x3)/(x2-x3)*y2+(x0-x2)/(x3-x2)*y3;


end
.
.
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 9th, 2021, 2:32 pm

.This function was left due to upper limit of characters in a single post. 
function [wMu0dt,wMu1dt,dwMu0dtdw,d2wMu0dtdw2,c1] = CalculateDriftAndVolA404(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt)

yy(wnStart:Nn)=((1-gamma)*w(wnStart:Nn)).^(1/(1-gamma));

Fp2=Fp1/(1-gamma);

wMu0dt(wnStart:Nn)=(YqCoeff0(1,1,2,1).*yy(wnStart:Nn).^Fp1(1,1,2,1)+ ...
    YqCoeff0(1,2,1,1).*yy(wnStart:Nn).^Fp1(1,2,1,1)+ ...
    YqCoeff0(2,1,1,1).*yy(wnStart:Nn).^Fp1(2,1,1,1))*dt + ...
    (YqCoeff0(1,1,3,1).*yy(wnStart:Nn).^Fp1(1,1,3,1)+ ...
    YqCoeff0(1,2,2,1).*yy(wnStart:Nn).^Fp1(1,2,2,1)+ ...
    YqCoeff0(2,1,2,1).*yy(wnStart:Nn).^Fp1(2,1,2,1)+ ...
    YqCoeff0(1,3,1,1).*yy(wnStart:Nn).^Fp1(1,3,1,1)+ ...
    YqCoeff0(2,2,1,1).*yy(wnStart:Nn).^Fp1(2,2,1,1)+ ...
    YqCoeff0(3,1,1,1).*yy(wnStart:Nn).^Fp1(3,1,1,1))*dt^2;% + ...
%     (YqCoeff0(1,1,4,1).*yy(wnStart:Nn).^Fp1(1,1,4,1)+ ...
%     YqCoeff0(1,2,3,1).*yy(wnStart:Nn).^Fp1(1,2,3,1)+ ...
%     YqCoeff0(2,1,3,1).*yy(wnStart:Nn).^Fp1(2,1,3,1)+ ...
%     YqCoeff0(1,3,2,1).*yy(wnStart:Nn).^Fp1(1,3,2,1)+ ...
%     YqCoeff0(2,2,2,1).*yy(wnStart:Nn).^Fp1(2,2,2,1)+ ...
%     YqCoeff0(3,1,2,1).*yy(wnStart:Nn).^Fp1(3,1,2,1)+ ...
%     YqCoeff0(1,4,1,1).*yy(wnStart:Nn).^Fp1(1,4,1,1)+ ...
%     YqCoeff0(2,3,1,1).*yy(wnStart:Nn).^Fp1(2,3,1,1)+ ...
%     YqCoeff0(3,2,1,1).*yy(wnStart:Nn).^Fp1(3,2,1,1)+ ...
%     YqCoeff0(4,1,1,1).*yy(wnStart:Nn).^Fp1(4,1,1,1))*dt^3;%+ ...
%     (YqCoeff0(1,1,5,1).*yy(wnStart:Nn).^Fp1(1,1,5,1)+ ...
%      YqCoeff0(1,2,4,1).*yy(wnStart:Nn).^Fp1(1,2,4,1)+ ...
%      YqCoeff0(2,1,4,1).*yy(wnStart:Nn).^Fp1(2,1,4,1)+ ...
%      YqCoeff0(2,1,1,1).*yy(wnStart:Nn).^Fp1(2,1,1,1)+ ...
%       YqCoeff0(2,2,3,1).*yy(wnStart:Nn).^Fp1(2,2,3,1)+ ...
%       YqCoeff0(3,1,3,1).*yy(wnStart:Nn).^Fp1(3,1,3,1)+ ...
%       YqCoeff0(1,4,2,1).*yy(wnStart:Nn).^Fp1(1,4,2,1)+ ...
%       YqCoeff0(2,3,2,1).*yy(wnStart:Nn).^Fp1(2,3,2,1)+ ...
%       YqCoeff0(3,2,2,1).*yy(wnStart:Nn).^Fp1(3,2,2,1)+ ...
%       YqCoeff0(4,1,2,1).*yy(wnStart:Nn).^Fp1(4,1,2,1)+ ...
%       YqCoeff0(1,5,1,1).*yy(wnStart:Nn).^Fp1(1,5,1,1)+ ...
%       YqCoeff0(2,4,1,1).*yy(wnStart:Nn).^Fp1(2,4,1,1)+ ...
%       YqCoeff0(3,3,1,1).*yy(wnStart:Nn).^Fp1(3,3,1,1)+  ...
%       YqCoeff0(4,2,1,1).*yy(wnStart:Nn).^Fp1(4,2,1,1)+ ...
%       YqCoeff0(5,1,1,1).*yy(wnStart:Nn).^Fp1(5,1,1,1))*dt^4;


wMu1dt(wnStart:Nn)=(YqCoeff0(1,1,3,1).*yy(wnStart:Nn).^Fp1(1,1,3,1)+ ...
    YqCoeff0(1,2,2,1).*yy(wnStart:Nn).^Fp1(1,2,2,1)+ ...
    YqCoeff0(2,1,2,1).*yy(wnStart:Nn).^Fp1(2,1,2,1)+ ...
    YqCoeff0(1,3,1,1).*yy(wnStart:Nn).^Fp1(1,3,1,1)+ ...
    YqCoeff0(2,2,1,1).*yy(wnStart:Nn).^Fp1(2,2,1,1)+ ...
    YqCoeff0(3,1,1,1).*yy(wnStart:Nn).^Fp1(3,1,1,1))*dt^2;% + ...



dwMu0dtdw(wnStart:Nn)=(YqCoeff0(1,1,2,1).*Fp1(1,1,2,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(1,1,2,1))+ ...
    YqCoeff0(1,2,1,1).*Fp1(1,2,1,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(1,2,1,1))+ ...
    YqCoeff0(2,1,1,1).*Fp1(2,1,1,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(2,1,1,1)))*dt + ...
    (YqCoeff0(1,1,3,1).*Fp1(1,1,3,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(1,1,3,1))+ ...
    YqCoeff0(1,2,2,1).*Fp1(1,2,2,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(1,2,2,1))+ ...
    YqCoeff0(2,1,2,1).*Fp1(2,1,2,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(2,1,2,1))+ ...
    YqCoeff0(1,3,1,1).*Fp1(1,3,1,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(1,3,1,1))+ ...
    YqCoeff0(2,2,1,1).*Fp1(2,2,1,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(2,2,1,1))+ ...
    YqCoeff0(3,1,1,1).*Fp1(3,1,1,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(3,1,1,1)))*dt^2;% + ...
%     (YqCoeff0(1,1,4,1).*Fp1(1,1,4,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(1,1,4,1))+ ...
%     YqCoeff0(1,2,3,1).*Fp1(1,2,3,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(1,2,3,1))+ ...
%     YqCoeff0(2,1,3,1).*Fp1(2,1,3,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(2,1,3,1))+ ...
%     YqCoeff0(1,3,2,1).*Fp1(1,3,2,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(1,3,2,1))+ ...
%     YqCoeff0(2,2,2,1).*Fp1(2,2,2,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(2,2,2,1))+ ...
%     YqCoeff0(3,1,2,1).*Fp1(3,1,2,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(3,1,2,1))+ ...
%     YqCoeff0(1,4,1,1).*Fp1(1,4,1,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(1,4,1,1))+ ...
%     YqCoeff0(2,3,1,1).*Fp1(2,3,1,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(2,3,1,1))+ ...
%     YqCoeff0(3,2,1,1).*Fp1(3,2,1,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(3,2,1,1))+ ...
%     YqCoeff0(4,1,1,1).*Fp1(4,1,1,1).*((1-gamma).*w(wnStart:Nn)).^(-1+Fp2(4,1,1,1)))*dt^3;


d2wMu0dtdw2(wnStart:Nn)=(1-gamma).*((YqCoeff0(1,1,2,1).*Fp1(1,1,2,1).*(-1+Fp2(1,1,2,1)).*((1-gamma).*w(wnStart:Nn)).^(-2+Fp2(1,1,2,1))+ ...
    YqCoeff0(1,2,1,1).*Fp1(1,2,1,1).*(-1+Fp2(1,2,1,1)).*((1-gamma).*w(wnStart:Nn)).^(-2+Fp2(1,2,1,1))+ ...
    YqCoeff0(2,1,1,1).*Fp1(2,1,1,1).*(-1+Fp2(2,1,1,1)).*((1-gamma).*w(wnStart:Nn)).^(-2+Fp2(2,1,1,1)))*dt + ...
    (YqCoeff0(1,1,3,1).*Fp1(1,1,3,1).*(-1+Fp2(1,1,3,1)).*((1-gamma).*w(wnStart:Nn)).^(-2+Fp2(1,1,3,1))+ ...
    YqCoeff0(1,2,2,1).*Fp1(1,2,2,1).*(-1+Fp2(1,2,2,1)).*((1-gamma).*w(wnStart:Nn)).^(-2+Fp2(1,2,2,1))+ ...
    YqCoeff0(2,1,2,1).*Fp1(2,1,2,1).*(-1+Fp2(2,1,2,1)).*((1-gamma).*w(wnStart:Nn)).^(-2+Fp2(2,1,2,1))+ ...
    YqCoeff0(1,3,1,1).*Fp1(1,3,1,1).*(-1+Fp2(1,3,1,1)).*((1-gamma).*w(wnStart:Nn)).^(-2+Fp2(1,3,1,1))+ ...
    YqCoeff0(2,2,1,1).*Fp1(2,2,1,1).*(-1+Fp2(2,2,1,1)).*((1-gamma).*w(wnStart:Nn)).^(-2+Fp2(2,2,1,1))+ ...
    YqCoeff0(3,1,1,1).*Fp1(3,1,1,1).*(-1+Fp2(3,1,1,1)).*((1-gamma).*w(wnStart:Nn)).^(-2+Fp2(3,1,1,1)))*dt^2);% + ...


c1(wnStart:Nn)=YqCoeff0(1,1,1,2).*yy(wnStart:Nn).^Fp1(1,1,1,2).*sqrt(dt)+ ...
    (YqCoeff0(1,1,2,2).*yy(wnStart:Nn).^Fp1(1,1,2,2)+YqCoeff0(1,2,1,2).*yy(wnStart:Nn).^Fp1(1,2,1,2)+ ...
    YqCoeff0(2,1,1,2).*yy(wnStart:Nn).^Fp1(2,1,1,2)).*dt^1.5;%+ ...
 

end
.
.
I will still come back with a better and commented version in hopefully a day. I hope things go well for me. I will request American friends to force mind control agency to please end my detention.
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 10th, 2021, 6:49 am

Dear friends, there is this new update in my research. I was earlier thinking (rather not thinking and only implicitly assuming) that median (Z=0) at time t of underlying normal will coincide with zero of Bessel variable(B=0) at time t+1, but when I look at CDF at B=0, it has a slight shift from median value of CDF=.5; This shift does not make much of a difference in the middle of the distribution but creates huge problems far in the tails. I will make the required alteration in my program and I hope that I would be able to get better results between 3 SD  to 5 SD of underlying normal. 
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 10th, 2021, 8:47 am

Friends, I am so excited to tell the good news that the algorithm now works perfectly from -5 SD to +5 SD of underlying normal. I will be making some minor changes and add comments and try to post it later today.
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 10th, 2021, 5:54 pm

Post in progress.
Here is the new main function with comments.
.
.
function [] = SDETransProb08WmtGrid200b49()

%Copyright Ahsan Amin. Infiniti derivatives Technologies.
%Please fell free to connect on linkedin: linkedin.com/in/ahsan-amin-0a53334 
%or skype ahsan.amin2999
%In this program, I am simulating the SDE given as
%dy(t)=mu1 x(t)^beta1 dt + mu2 x(t)^beta2 dt +sigma x(t)^gamma dz(t)

%I have not directly simulated the SDE but simulated the transformed 
%Besse1 process version of the SDE and then changed coordinates to retreive
%the SDE in original coordinates.
%The present program will analytically evolve only the Bessel Process version of the
%SDE in transformed coordinates.

%In this program, I have simulated the density for first sixteen time
%intervals using a simple method. After first sixteen intervals, I start
%simulating with probability mass transfer method. I am presenting a
%simpler version which is easier to understand. I have advanced the density
%here for only two steps with mass transfer method. 17 to 18 intervals.
%My extrapolations at the boundaries are not very good and I suggest that
%you use your favorite method for that. Same for caclualtion of higher
%order derivatives. With above improvements, you can easily continue the
%method for whatever number of steps. Please experiment with step size and
%you will find the method robust enough. This is just an early version and
%I will be coming with better versions soon.

%In this mass transfer version, I have calculated centre of the distribution
%at time t+1 and then move to the right by assigning a trial boundary to each cell and
%then probability mass in each cell at time t+1 with trial boundary is
%calculated. The small defect in true probability mass and calculated
%probability mass is used with derivatives to calculate the exact boundary.
%Then we repeat the algorithm from left of zero towards -6 SD.
%The present version is a serial algorithm. A better algorithm would be a
%parallel algorithm that would simply assign a trial boundary and one CDF
%value associated with that trial boundary instead of calculating CDF on
%both boundaries and then equating probability mass in each cell serially.
%Since I started working with this version, I retained it but in next
%version, I will make it a cheaper algorithm that will be very simple to
%parallelize.

dt=.125/16/2/2/2;   % Simulation time interval.%Fodiffusions close to zero
             %decrease dt for accuracy.

%T=Tt*dt;
Tt=18;
T=Tt*dt;
OrderA=4;  %
dtM=dt;%.125/2/4;%Monte carlo time interval size dtM.
TtM=Tt;%T*2*8*4;%Monte carlo number of simulation intervals.



dNn=.05;   % Normal density subdivisions width. would change with number of subdivisions
Nn=200;  % No of normal density subdivisions
NnMidl=100;%One half density Subdivision left from mid of normal density(low)
NnMidh=101;%One half density subdivision right from the mid of normal density(high)
NnMid=4.0;

Z(1:Nn)=(((1:Nn)-20.5)*dNn-NnMid)

%There are two indices. One goes to Nn=200. This is used for calculation of
%SDE simulation at next time level t+1. This covers -5 to +5 SDs of
%underlying Z.
%Second index Nn1 below goes from 1 to 240. This covers -6 to +6 SD of
%underlying Z. In probability mass transfer methos, we simulate the SDE
%from -5 SD to +5 SD and then extrapolate on both sides so that we have a
%new grid from -6 SD to +6 SD(1:Nn1). This extrapolated grid(which is assigned time t)
%is used to calculate the time t+1 grid from -5 SD to +5 SD(1:Nn).
%Grid spacing is the same on both grids.
Nn1=240;
%dNn1=.05;
Nn1Midl=120;
Nn1Midh=121;
Nn1Mid=6.025;

Z1(1:Nn1)=((1:Nn1)*dNn-Nn1Mid)
Z1Prob(1)=normcdf(-5.95)-normcdf(-6.0);
Z1Prob(Nn1)=normcdf(6.0)-normcdf(5.95);
Z1Prob(2:Nn1-1)=normcdf(.5*Z1(2:Nn1-1)+.5*Z1(3:Nn1),0,1)-normcdf(.5*Z1(2:Nn1-1)+.5*Z1(1:Nn1-2),0,1);

ZProb(1:Nn)=Z1Prob(21:Nn1-20);
Z(1:Nn)=Z1(21:Nn1-20);


sum(Z1Prob(1:Nn1))
sum(ZProb(1:Nn))
str=input('Look at Zs');

x0=.100;   % starting value of SDE
beta1=0.0;
beta2=1.00;   % Second drift term power.
gamma=.5;%50;   % volatility power.                                                                                                                                                                                                                                                                     
kappa=2.0;%.950;   %mean reversion parameter.
theta=1.0;%mean reversion target
sigma0=.850;%Volatility value

%you can specify any general mu1 and mu2 and beta1 and beta2.
mu1=+1*theta*kappa;   %first drift coefficient.
mu2=-1*kappa;    % Second drift coefficient.
%mu1=0;
%mu2=0;

alpha=1;% x^alpha is being expanded. This is currently for monte carlo only.
alpha1=1-gamma;%This is for expansion of integrals for calculation of drift 
%and volatility coefficients
                
w(1:Nn)=x0^(1-gamma)/(1-gamma);

Z
Z1
str=input('Look at Zs');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

sigma11(1:OrderA+1)=0;
mu11(1:OrderA+1)=0;
mu22(1:OrderA+1)=0;
sigma22(1:OrderA+1)=0;
% index 1 correponds to zero level since matlab indexing starts at one. 
sigma11(1)=1;
mu11(1)=1;
mu22(1)=1;
sigma22(1)=1;


mu33(1)=1;
mu44(1)=1;
mu33(2:OrderA+1)=0;
mu44(2:OrderA+1)=0;

for k=1:(OrderA+1)
    if sigma0~=0
        sigma11(k)=sigma0^(k-1);
    end
    if mu1 ~= 0
        mu11(k)=mu1^(k-1);
    end
    if mu2 ~= 0
        mu22(k)=mu2^(k-1);
    end
    if sigma0~=0
        sigma22(k)=sigma0^(2*(k-1));
    end
end
%Ft(1:TtM+1,1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0; %General time powers on hermite polynomials
Fp(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;%General x powers on coefficients of hermite polynomials.
Fp1(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;%General x powers for bessel transformed coordinates.

%YCoeff0 and YCoeff are coefficents for original coordinates monte carlo.
%YqCoeff0 and YqCoeff are bessel/lamperti version monte carlo.

YCoeff0(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;
YqCoeff0(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;
%Pre-compute the time and power exponent values in small multi-dimensional arrays
YCoeff = ItoTaylorCoeffsNew(alpha,beta1,beta2,gamma); %expand y^alpha where alpha=1;
YqCoeff = ItoTaylorCoeffsNew(alpha1,beta1,beta2,gamma);%expand y^alpha1 where alpha1=(1-gamma)
YqCoeff=YqCoeff/(1-gamma); %Transformed coordinates coefficients have to be 
%further divided by (1-gamma)

for k = 0 : (OrderA)
    for m = 0:k
        l4 = k - m + 1;
        for n = 0 : m
            l3 = m - n + 1;
            for j = 0:n
                l2 = n - j + 1;
                l1 = j + 1;
                %Ft(l1,l2,l3,l4) = dtM^((l1-1) + (l2-1) + (l3-1) + .5* (l4-1));
                Fp(l1,l2,l3,l4) = (alpha + (l1-1) * beta1 + (l2-1) * beta2 + (l3-1) * 2* gamma + (l4-1) * gamma ...
                    - (l1-1) - (l2-1) - 2* (l3-1) - (l4-1));
                Fp1(l1,l2,l3,l4) = (alpha1 + (l1-1) * beta1 + (l2-1) * beta2 + (l3-1) * 2* gamma + (l4-1) * gamma ...
                    - (l1-1) - (l2-1) - 2* (l3-1) - (l4-1));
                
                YCoeff0(l1,l2,l3,l4) =YCoeff(l1,l2,l3,l4).*mu11(l1).*mu22(l2).*sigma22(l3).*sigma11(l4);
                YqCoeff0(l1,l2,l3,l4) =YqCoeff(l1,l2,l3,l4).*mu11(l1).*mu22(l2).*sigma22(l3).*sigma11(l4);
                YqzCoeff0(l1,l2,l3,l4) =YqCoeff(l1,l2,l3,l4).*mu33(l1).*mu44(l2).*sigma22(l3).*sigma11(l4);
            end
        end
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


wnStart=1;%
yy(wnStart:Nn)=((1-gamma)*w(wnStart:Nn)).^(1/(1-gamma));
%The above yy(wnStart:Nn)=x0;

tic


for tt=1:Tt 
    t2=tt*dt;
    t1=(tt-1)*dt;
    if(tt==1)
       
        [wMu0dt,c1,c22] = CalculateDriftAndVolA8Trans(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt);
        w(1:Nn)=x0^(1-gamma)/(1-gamma)+wMu0dt(1)+c1(1).*Z(1:Nn);
        

    end
    if((tt>1) && (tt<=16))
        %The first sixteen steps are simulated using a simple and slightly
        %altered version of the method I have used for simple CEV noises
        %and brownian motions. I used it only for starting few time steps
        %since density remains pretty much very close to linear here. If
        %that is not the case, you would have to alter this.
       [wMu0dt,wMu1dt,dwMu0dtdw,d2wMu0dtdw2,c1] = CalculateDriftAndVolA404(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt);
        %dw(wnStart:Nn)=c1(wnStart:Nn);%.*Z(wnStart:Nn) ;% ...
       dw(wnStart:Nn)=c1(wnStart:Nn).*Z(wnStart:Nn) ;% ...
       dw2(wnStart:Nn)=dw(wnStart:Nn).^2;
       [wMid] = InterpolateOrderN8(8,0,Z(NnMidl-3),Z(NnMidl-2),Z(NnMidl-1),Z(NnMidl),Z(NnMidh),Z(NnMidh+1),Z(NnMidh+2),Z(NnMidh+3),w(NnMidl-3),w(NnMidl-2),w(NnMidl-1),w(NnMidl),w(NnMidh),w(NnMidh+1),w(NnMidh+2),w(NnMidh+3));
       B(1:Nn)=w(1:Nn)-wMid;
       [dBdZ,d2BdZ2,d3BdZ3] = First3Derivatives2ndOrderEqSpacedA(wnStart,Nn,dNn,B,Z);
       B(wnStart:Nn)=sign(B(wnStart:Nn)+dw(wnStart:Nn)).* ...
            sqrt(abs(sign(B(wnStart:Nn)).*(B(wnStart:Nn)).^2+ ...
            sign(dw(wnStart:Nn)).*dw2(wnStart:Nn)));
        
        w(wnStart:Nn)=wMid+wMu0dt(wnStart:Nn)+B(wnStart:Nn);
        
        
        
    end
    %Now starts the calculation for SDE simulation using probability mass
    %transfer.
    if(tt>16)
                
        [wMu0dt,wMu1dt,dwMu0dtdw,d2wMu0dtdw2,c1] = CalculateDriftAndVolA404(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt); 
      
        dw(wnStart:Nn)=c1(wnStart:Nn) ;% ...
        dw2(wnStart:Nn)=dw(wnStart:Nn).^2;
        %[wMid] = InterpolateOrderN6(6,0,Z(NnMidl-2),Z(NnMidl-1),Z(NnMidl),Z(NnMidh),Z(NnMidh+1),Z(NnMidh+2),w(NnMidl-2),w(NnMidl-1),w(NnMidl),w(NnMidh),w(NnMidh+1),w(NnMidh+2));
        [wMid] = InterpolateOrderN8(8,0,Z(NnMidl-3),Z(NnMidl-2),Z(NnMidl-1),Z(NnMidl),Z(NnMidh),Z(NnMidh+1),Z(NnMidh+2),Z(NnMidh+3),w(NnMidl-3),w(NnMidl-2),w(NnMidl-1),w(NnMidl),w(NnMidh),w(NnMidh+1),w(NnMidh+2),w(NnMidh+3));
        B(1:Nn)=w(1:Nn)-wMid;
        B1=B;
        [dBdZ_0,d2BdZ2_0,d3BdZ3_0] = First3Derivatives2ndOrderEqSpacedA(wnStart,Nn,dNn,B,Z);
        %Above are derivative names with an appended zero "_0". These are derivatives on the 
        %Nn grid (time t+1 grid). When there are no appended zeros, those are
        %derivatives on the Nn1 grid i.e time t grid.
       
     
        if(tt<=32)
            for nn=1:20
                xx0(nn)=Z(1)-nn*dNn;  %Z values corresponding to points to be extrapolated.
                xx1(nn)=Z(nn);        %Z Values corresponding to boundary points used to extrapolate.%We use only first ten out of 20.
                yy1(nn)=B1(nn);       %resultant values for points used to extrapolate.%We use only first ten out of 20.
            end
            %%[yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            %In the loop below, the interpolated values are assigned to
            %variable BB1 which extends form 1:Nn1. We would use this
            %variable BB1(Bm(t) in the notes) later as values at time t to simulate the values
            %of Bn at time t+1.
            for nn=1:20
                BB1(21-nn)=yy0(nn);
                %%BB1(21-nn)=Btemp-yy0(nn)*dNn;
                %%Btemp=BB1(21-nn);
            end
            %In the loop below main body of the variable is allocated to
            %the array BB1 in notes "Bm(t)"
            for nn=1:Nn
                BB1(nn+20)=B1(nn); 
            end
            
            %Below we do extrapolation on right boundary from 5SD to 6 SD
            %and then assign it to BB1 which is Bm(t).
            for nn=1:20
                xx0(nn)=Z(Nn)+nn*dNn;
                xx1(nn)=Z(Nn-nn+1);
                %%yy1(nn)=dBdZ_0(Nn-nn+1);
                yy1(nn)=B1(Nn-nn+1);
            end
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            
            for nn=1:20
                BB1(Nn+20+nn)=yy0(nn);
                
            end
            
            %The function below calculates grid cell boundaries from mid
            %points of the grids using interpolation and relevant Z. The
            %grid is equidistant and symmetric with respect to underlying Z
            %but not with respect to the Bessel variable. We use the value
            %of Z at boundaries of each cell to interpolate the value of
            %bessel variable there.
            [BB1a,BB1b] = CalculateGridStartsAndEndsBoundedEnds(BB1,Z1,1,Nn1,dNn);
            
            %Below,I later assigned Z1 to ZZ1 and N1 to NN1 ans similarly for
            %Z1Prob since earlier I had several(three different) cases of 
            %extrapolation ranging from 5 to 6 SD, and 5 to 5.5 SD and 5 to 5.25 SD.
            %I Was thinking when time would advance and grid would have
            %expanded and if dt would stay the same, the user might be
            %better off choosing a smaller grid with better extrapolation. 
            
            ZZ1=Z1;
            NN1=Nn1;
            ZZProb(1:NN1)=Z1Prob(1:Nn1);
        end
            %plot(ZZ1(1:NN1),BB1(1:NN1),'b',ZZ1(1:NN1),BB1a(1:NN1),'y',ZZ1(1:NN1),BB1b(1:NN1),'k',Z(1:Nn),B1(1:Nn),'r')
            %str=input('Look at B1 and BB1, original and extrapolated version and boundaries');
            
            %Below calculate first four derivatives. Please replace with your favorite
            %robust function. 
            [dBdZ,d2BdZ2,d3BdZ3] = First3Derivatives2ndOrderEqSpacedA(1,NN1,dNn,BB1,Z1);
            [dwdZAA,d2wdZ2AA,d3wdZ3AA,d4BdZ4] = First4Derivatives2ndOrderEqSpaced(1,NN1,dNn,BB1,Z1);
        
            %plot((1:NN1),dBdZ(1:NN1),'r')
            %str=input('Look at 1st derivative');
            %plot((1:NN1),d2BdZ2(1:NN1),'r')
            %str=input('Look at 2nd derivative');
            %plot((1:NN1),d3BdZ3(1:NN1),'r')
            %str=input('Look at 3rd derivative');
        
            %Below calculate hermite polynomials of Z1 underlying the 
            %Grid BB1 which is "Bm(t)" grid. We will use these hermite 
            %polynomials and later derivatives to calculate the derivatives of 
            %density of Bm with respect to Bm. dpdBm calcualted at centre
            %of the grid cells. 
       
            He1(1:NN1)=Z1(1:NN1);
            He2(1:NN1)=Z1(1:NN1).^2-1;
            He3(1:NN1)=Z1(1:NN1).^3-3*Z1(1:NN1);
            He4(1:NN1)=Z1(1:NN1).^4-6*Z1(1:NN1).^2+3;
            He5(1:NN1)=Z1(1:NN1).^5-10*Z1(1:NN1).^3+15;
            Zpdf(1:NN1)=normpdf(Z1(1:NN1),0,1);
            dZpdf(1:NN1)=-He1(1:NN1).*Zpdf(1:NN1);
            d2Zpdf(1:NN1)=He2(1:NN1).*Zpdf(1:NN1);
            d3Zpdf(1:NN1)=-He3(1:NN1).*Zpdf(1:NN1);
            d4Zpdf(1:NN1)=He4(1:NN1).*Zpdf(1:NN1);
            d5Zpdf(1:NN1)=-He5(1:NN1).*Zpdf(1:NN1);

            %Please note that in calculations below, we are using derivatives without 
            %appended zeros since they are on BB1 "Bm(t)" grid that ranges from 1:Nn1 or equivalently 1:NN1. 
            dZdB(1:NN1)=1.0./dBdZ(1:NN1);
            d2ZdB2(1:NN1)=-d2BdZ2(1:NN1).*dZdB(1:NN1).^3;
            d3ZdB3(1:NN1)=-d3BdZ3(1:NN1).*dZdB(1:NN1).^4+3*d2BdZ2(1:NN1).^2.*dZdB(1:NN1).^5;
            d4ZdB4(1:NN1)=-d4BdZ4(1:NN1).*dZdB(1:NN1).^5-4*d3BdZ3(1:NN1).*d2ZdB2(1:NN1).*dZdB(1:NN1).^3+ ...
            6*d2BdZ2(1:NN1).*d3BdZ3(1:NN1).*dZdB(1:NN1).^6+15*d2BdZ2(1:NN1).^2.*d2ZdB2(1:NN1).*dZdB(1:NN1).^6 ;
            d5ZdB5(1:NN1)=0.0;
            d6ZdB6(1:NN1)=0.0;
       
       
            
            pm0(1:NN1)=Zpdf(1:NN1).*dZdB(1:NN1);
            dpm0(1:NN1)=dZpdf(1:NN1).*dZdB(1:NN1).^2+Zpdf(1:NN1).*d2ZdB2(1:NN1);
            d2pm0(1:NN1)=d2Zpdf(1:NN1).*dZdB(1:NN1).^3+3*dZpdf(1:NN1).*dZdB(1:NN1).*d2ZdB2(1:NN1)+Zpdf(1:NN1).*d3ZdB3(1:NN1);
            d3pm0(1:NN1)=d3Zpdf(1:NN1).*dZdB(1:NN1).^4+6*d2Zpdf(1:NN1).*dZdB(1:NN1).^2.*d2ZdB2(1:NN1) + ...
                4*dZpdf(1:NN1).*dZdB(1:NN1).*d3ZdB3(1:NN1) + 3*dZpdf(1:NN1).*d2ZdB2(1:NN1).^2+ Zpdf(1:NN1).*d4ZdB4(1:NN1);
    
            d4pm0(1:NN1)=d4Zpdf(1:NN1).*dZdB(1:NN1).^5+10*d3Zpdf(1:NN1).*dZdB(1:NN1).^3.*d2ZdB2(1:NN1) + ...
                15*d2Zpdf(1:NN1).*dZdB(1:NN1).*d2ZdB2(1:NN1).^2 + ...
                10*d2Zpdf(1:NN1).*dZdB(1:NN1).^2.*d3ZdB3(1:NN1) + ...
                10*dZpdf(1:NN1).*d2ZdB2(1:NN1).*d3ZdB3(1:NN1) + ...
                5*dZpdf(1:NN1).*dZdB(1:NN1).*d4ZdB4(1:NN1)+ Zpdf(1:NN1).*d5ZdB5(1:NN1);
        
            d5pm0(1:NN1)=d5Zpdf(1:NN1).*dZdB(1:NN1).^6+15*d4Zpdf(1:NN1).*dZdB(1:NN1).^4.*d2ZdB2(1:NN1) + ...
                45*d3Zpdf(1:NN1).*dZdB(1:NN1).^2.*d2ZdB2(1:NN1).^2 + ...
                20*d3Zpdf(1:NN1).*dZdB(1:NN1).^3.*d3ZdB3(1:NN1) + ...
                15*d2Zpdf(1:NN1).*d2ZdB2(1:NN1).^3 + ...
                60*d2Zpdf(1:NN1).*dZdB(1:NN1).*d2ZdB2(1:NN1).*d3ZdB3(1:NN1) + ...
                15*d2Zpdf(1:NN1).*d2ZdB2(1:NN1).^2.*d4ZdB4(1:NN1)+ ...
                10*dZpdf(1:NN1).*d3ZdB3(1:NN1).^2+ ...
                15*dZpdf(1:NN1).*d2ZdB2(1:NN1).*d4ZdB4(1:NN1)+ ...
                6*dZpdf(1:NN1).*dZdB(1:NN1).*d5ZdB5(1:NN1)+ ...
                Zpdf(1:NN1).*d6ZdB6(1:NN1);
   
    
            %str=input('Look at derivatives of initial probability');
            %Below I reconstruct the new variable ww1(1:Nn1)=w(1:NN1) which is an
            %extrapolated version of w(1:Nn). I have used a first order
            %improved version that is still locally gaussian but has
            %slightly different variance across the grid. I might change it
            %in new later versions and use a gaussian grid with dt variance on
            %which even non-bessel coordinate variables in original coordinates would
            %be possibly simulated. ww1 is reconstructed by adding the mean
            %we had subtracted.
            
            ww1(1:NN1)=BB1(1:NN1)+wMid;
            %cc1 below is volatility associated with each grid cell at time
            %t Bm(t) or BB1.
            [wwMu0dt,wwMu1dt,wdwMu0dtdw,wd2wMu0dtdw2,cc1] = CalculateDriftAndVolA404(ww1,1,NN1,YqCoeff0,Fp1,gamma,dt); 
            %plot(ZZ1(1:NN1),ww1(1:NN1),'b',Z(1:Nn),w(1:Nn),'r')
            %str=input('Look at comparison of interpolated and original w-0');
            %plot(ZZ1(1:NN1),cc1(1:NN1),'b',Z(1:Nn),c1(1:Nn),'r')
            %str=input('Look at comparison of original and interpolated vol coefficient-1');
            %plot(ZZ1(1:NN1),cc1(1:NN1),'b',Z(1:Nn),c1(1:Nn),'r')
            %str=input('Look at comparison of original and interpolated vol coefficient-1A');
            %plot(ZZ1(1:NN1),wwMu0dt(1:NN1),'b',Z(1:Nn),wMu0dt(1:Nn),'r')
            %str=input('Look at drifts origianl and interpolated-2');
            %plot(ZZ1(1:NN1),ZZProb(1:NN1),'b',Z(1:Nn),ZProb(1:Nn),'r')
            %str=input('Look at Zprobss -3');
            %plot((1:Nn),Z(1:Nn),'r',(1:NN1)-20,ZZ1(1:NN1),'b')
            %str=input('Look at Zs -4');
       
            %Below are calculations of CDF and its derivatives to calculate
            %the mid point of the grid at time t+1. This mid point should
            %lie exactly on median which means CDF there would be exactly
            %equal to .5 or CDF=.5.
            PoutMid=0;
            poutMid=0;
            dpoutdBMid=0.0;
            d2poutdB2Mid=0.0;
            d3poutdB3Mid=0.0;
       
            for mm=1:NN1
                %0.0 as argument is the trial guess where CDF and
                %derivatives are calculated.
                [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(0.0,cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
                %Sometimes due to my bad extrapolation at boundaries, some
                %values at extreme boundary were NAN so I added this fix.
                if(isnan(Pmn)==1)
                    Pmn=0;
                    pmn=0;
                    dpmn=0;
                    d2pmn=0;
                    d3pmn=0;
                end
            
                %Below is summation of CDF from each cell at mid trial point. 
                %And so on for derivatives of CDF. dCDFdBn. d2CDFdBn2.and so
                %on.
                PoutMid=PoutMid+ Pmn;
                poutMid=poutMid+pmn;
                dpoutdBMid=dpoutdBMid+dpmn;
                d2poutdB2Mid=d2poutdB2Mid+d2pmn;
                d3poutdB3Mid=d3poutdB3Mid+d3pmn;
                   
            end
            ExcessCDF=PoutMid-.5;
            %Below +1 flag is used when we are finding CDF towards right side.
            %At Right boundary.
            [dB] =SolveQuarticRootForProb(ExcessCDF,poutMid,dpoutdBMid,d2poutdB2Mid,d3poutdB3Mid,+1);
            dB=real(dB);
            dB
            BnMid=dB; %The true value of median for Bn(t+1)
            str=input('Look at dB at median');
      
            %Now We calculate the right boundary of each cell from 0 SD to +5SD
            %B2a with an appended "a" is the left boundary.
            %B2b with an appended "b" is the right boundary.
            B2a(NnMidh)=BnMid;%  
            %I used this to calculate the cumulative defect in CDF towards the
            %right side.
            TotalExcessCDF2=0;
       
            for nn=NnMidh:Nn  %Loop to the right from 0 SD to +5 SD over Bn(t+1).
            % Below is the good guess for dBndZ of the cell. This requires
            % multiplication with dNn.  dNn means dZ here.
            %Please note that we are using derivative with an appended zero
            %since this calculation is on grid 1:Nn: Bn(t+1,1:Nn)
            SigmaB(nn)=sqrt(dBdZ_0(nn).^2+ dw2(nn));
           
            %B3 is only an auxiliary variable.
            if(nn==NnMidh)
                B3(nn)=BnMid+ SigmaB(nn).*dNn/2;
            else
                B3(nn)=B3(nn-1)+SigmaB(nn).*dNn;
            end
            
            
            %B2(nn)=B2a(nn)+SigmaB(nn).*dNn/2;
            %Below is the guesses trial right boundary that we will try to
            %improve.
            B2b(nn)=B2a(nn)+SigmaB(nn).*dNn;

            PIn(nn)=0;
            Pout(nn)=0;
            pout(nn)=0;
            dpoutdB(nn)=0.0;
            d2poutdB2(nn)=0.0;
            d3poutdB3(nn)=0.0;
            for mm=1:NN1
               %I wrote this function to calculate CDF at left boundary
               %where derivatives are not needed.
               [Pmn] = CalculateCDFFromSubDiv(B2a(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
               
               if(isnan(Pmn)==1)
                Pmn=0;
               end
               PIn(nn)=PIn(nn)+ Pmn; %This is CDF at left boundary
               %Below the function calculates CDF and its derivatives
               %at right boundary where all derivatives are needed.
               [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
                   
               if(isnan(Pmn)==1)
                    Pmn=0;
                    pmn=0;
                    dpmn=0;
                    d2pmn=0;
                    d3pmn=0;
                end
                Pout(nn)=Pout(nn)+ Pmn;
                pout(nn)=pout(nn)+pmn;
                dpoutdB(nn)=dpoutdB(nn)+dpmn;
                d2poutdB2(nn)=d2poutdB2(nn)+d2pmn;
                d3poutdB3(nn)=d3poutdB3(nn)+d3pmn;
                   
            end
            ExcessCDF=(Pout(nn)-PIn(nn))-ZProb(nn);
       
            [dB] =SolveQuarticRootForProb(ExcessCDF,pout(nn),dpoutdB(nn),d2poutdB2(nn),d3poutdB3(nn),+1);
            %dB is how much to move the trial boundary so that probability
            %defect goes to zero
            dB=real(dB);

            B2b(nn)=B2b(nn)+dB;

            if(nn<Nn)
                B2a(nn+1)=B2b(nn);
            end
            %Below I made calculations to recalculate the CDF on improved
            %boundary to see how much the defect is after making adjustment
            %to trial boundary. This is not necessary.
            Pout2(nn)=0.0;
            for mm=1:NN1
               [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
                   if(isnan(Pmn)==1)
                       Pmn=0;
                       pmn=0;
                       dpmn=0;
                       d2pmn=0;
                       d3pmn=0;
                   end
                   Pout2(nn)=Pout2(nn)+ Pmn; 
            end
            %ExcessCDF2 below is the probability mass defect after boundary
            %improvment.
            ExcessCDF2=(Pout2(nn)-PIn(nn))-ZProb(nn);
            %TotalExcessCDF2 measures cumulative error in cdf and loops
            %over all cells to the right of median.
            TotalExcessCDF2=TotalExcessCDF2+ExcessCDF2;

%            ZProb(nn)
%            ExcessCDF
%            ExcessCDF2
%            TotalExcessCDF2
%            dB
%            nn
 %       str=input('Look nos-end');    
            
            
       end
       
       %Now we repeat the trial boundary improvement procedure to the left
       %of median 
       
       %B2b(nn) is right boundary here.
       B2b(NnMidl)=BnMid;
       for nn=NnMidl:-1:1
           % Below is the good guess for dBndZ of the cell. This requires
           % multiplication with dNn. dNn means dZ here.
           %Please note that we are using derivative with an appended zero
           %since this calculation is on grid 1:Nn: Bn(t+1,1:Nn)
             
            SigmaB(nn)=sqrt(dBdZ_0(nn).^2+ dw2(nn));
            if(nn==NnMidl)
                B3(nn)=BnMid-SigmaB(nn).*dNn/2;
            else
                B3(nn)=B3(nn+1)-SigmaB(nn).*dNn;
            end
            %B2(nn)=B2b(nn)-SigmaB(nn).*dNn/2;
            %Trial left boundary below
            B2a(nn)=B2b(nn)-SigmaB(nn).*dNn;
            PIn(nn)=0;
            Pout(nn)=0.0;
            pin(nn)=0;
            dpindB(nn)=0.0;
            d2pindB2(nn)=0.0;
            d3pindB3(nn)=0.0;
            for mm=1:NN1
                  [Pmn] = CalculateCDFFromSubDiv(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));

                  if(isnan(Pmn)==1)
                       Pmn=0;
                   end
                    
                    Pout(nn)=Pout(nn)+ Pmn;

                    [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(B2a(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
 
                   if(isnan(Pmn)==1)
                       Pmn=0;
                       pmn=0;
                       dpmn=0;
                       d2pmn=0;
                       d3pmn=0;
                   end 
                   PIn(nn)=PIn(nn)+ Pmn;
                   
                   pin(nn)=pin(nn)+pmn;
                   dpindB(nn)=dpindB(nn)+dpmn;
                   d2pindB2(nn)=d2pindB2(nn)+d2pmn;
                   d3pindB3(nn)=d3pindB3(nn)+d3pmn;
            end
            ExcessCDF=(Pout(nn)-PIn(nn))-ZProb(nn);
            %nn
            %ZProb(nn)
            %ExcessCDF
            %pout(nn)
            %dpoutdB(nn)
            %negative one "-1" flag for negative side.
            [dB] =SolveQuarticRootForProb(ExcessCDF,pin(nn),dpindB(nn),d2pindB2(nn),d3pindB3(nn),-1);
            dB=real(dB);
            %str=input('Look at numbers in second part')
            B2a(nn)=B2a(nn)+dB;
            if(nn>1)
            B2b(nn-1)=B2a(nn);
            end
       end

%       
%       plot((1:Nn),SigmaB(1:Nn),'b');
%       str=input('Look at SigmaB');
       
       
%Below we calculate the mid points of grid cells from grid boundaries.       
       [B2] = CalculateGridSubs(B2a,B2b,Z,wnStart,Nn,dNn);
       
%Below B1 is old Bm(t). B2 is Bn(t+1). B3 is guessed Bn(t+1)(improved version since it is built on true deviations)
       plot((1:Nn),B1(1:Nn),'r',(1:Nn),B2(1:Nn),'b',(1:Nn),B3(1:Nn),'k')
       str=input('Look at comparison of new and old Bs');
       
%Below we reconstruct wn from Bn by adding wmid and the drift.        
       w(wnStart:Nn)=wMid+wMu0dt(wnStart:Nn)+B2(wnStart:Nn);
%Below is the grsph of newly calculated value of w.       
       plot((1:Nn),w(1:Nn),'r')
       str=input('Calculated Value of w');
    end
end
    

w1=w;

%below D's (the names of variables starting with D) are 
%change of probability derivatives.

y_w(1:Nn)=0;
y_w(wnStart:Nn) = ((1-gamma)*w(wnStart:Nn)).^(1/(1-gamma));
y_w1(1:Nn)=0;
y_w1(wnStart:Nn) = ((1-gamma)*w1(wnStart:Nn)).^(1/(1-gamma));
Dfy_w(wnStart:Nn)=0;
Dfy_w1(wnStart:Nn)=0;
for nn=wnStart+1:Nn-1
    Dfy_w(nn) = (y_w(nn + 1) - y_w(nn - 1))/(Z(nn + 1) - Z(nn - 1));
    Dfy_w1(nn) = (y_w1(nn + 1) - y_w1(nn - 1))/(Z(nn + 1) - Z(nn - 1));
    %Change of variable derivative for densities
end
py_w(1:Nn)=0;
py_w1(1:Nn)=0;
for nn = wnStart:Nn-1
    py_w(nn) = (normpdf(Z(nn),0, 1))/abs(Dfy_w(nn));%Origianl coordinates density
    py_w1(nn) = (normpdf(Z(nn),0, 1))/abs(Dfy_w1(nn));
end

toc

ItoHermiteMean=sum(y_w(wnStart+1:Nn-1).*ZProb(wnStart+1:Nn-1)) %Original process average from coordinates 
disp('true Mean only applicable to standard SV mean reverting type models otherwise disregard');
TrueMean=theta+(x0-theta)*exp(-kappa*dt*Tt)%Mean reverting SDE original variable true average

rng(29079137, 'twister')
paths=200000;
YY(1:paths)=x0;  %Original process monte carlo.
Random1(1:paths)=0;
for tt=1:TtM
    
    Random1=randn(size(Random1));
    HermiteP1(1,1:paths)=1;
    HermiteP1(2,1:paths)=Random1(1:paths);
    HermiteP1(3,1:paths)=Random1(1:paths).^2-1;
    HermiteP1(4,1:paths)=Random1(1:paths).^3-3*Random1(1:paths);
    HermiteP1(5,1:paths)=Random1(1:paths).^4-6*Random1(1:paths).^2+3;
    

    YY(1:paths)=YY(1:paths) + ...
        (YCoeff0(1,1,2,1).*YY(1:paths).^Fp(1,1,2,1)+ ...
        YCoeff0(1,2,1,1).*YY(1:paths).^Fp(1,2,1,1)+ ...
        YCoeff0(2,1,1,1).*YY(1:paths).^Fp(2,1,1,1))*dtM + ...
        (YCoeff0(1,1,3,1).*YY(1:paths).^Fp(1,1,3,1)+ ...
        YCoeff0(1,2,2,1).*YY(1:paths).^Fp(1,2,2,1)+ ...
        YCoeff0(2,1,2,1).*YY(1:paths).^Fp(2,1,2,1)+ ...
        YCoeff0(1,3,1,1).*YY(1:paths).^Fp(1,3,1,1)+ ...
        YCoeff0(2,2,1,1).*YY(1:paths).^Fp(2,2,1,1)+ ...
        YCoeff0(3,1,1,1).*YY(1:paths).^Fp(3,1,1,1))*dtM^2 + ...
        ((YCoeff0(1,1,1,2).*YY(1:paths).^Fp(1,1,1,2).*sqrt(dtM))+ ...
        (YCoeff0(1,1,2,2).*YY(1:paths).^Fp(1,1,2,2)+ ...
        YCoeff0(1,2,1,2).*YY(1:paths).^Fp(1,2,1,2)+ ...
        YCoeff0(2,1,1,2).*YY(1:paths).^Fp(2,1,1,2)).*dtM^1.5) .*HermiteP1(2,1:paths) + ...
        ((YCoeff0(1,1,1,3).*YY(1:paths).^Fp(1,1,1,3) *dtM) + ...
        (YCoeff0(1,1,2,3).*YY(1:paths).^Fp(1,1,2,3)+ ...
        YCoeff0(1,2,1,3).*YY(1:paths).^Fp(1,2,1,3)+ ...
        YCoeff0(2,1,1,3).*YY(1:paths).^Fp(2,1,1,3)).*dtM^2).*HermiteP1(3,1:paths) + ...
        ((YCoeff0(1,1,1,4).*YY(1:paths).^Fp(1,1,1,4)*dtM^1.5 )).*HermiteP1(4,1:paths) + ...
        (YCoeff0(1,1,1,5).*YY(1:paths).^Fp(1,1,1,5)*dtM^2.0).*HermiteP1(5,1:paths);
    

end

YY(YY<0)=0;
disp('Original process average from monte carlo');
MCMean=sum(YY(:))/paths %origianl coordinates monte carlo average.
MCVar=sum((YY(:)-MCMean).^2)/paths
disp('Original process average from our simulation');
ItoHermiteMean=sum(y_w(wnStart+1:Nn-1).*ZProb(wnStart+1:Nn-1)) %Original process average from coordinates 
ItoHermiteVar=sum((y_w(wnStart+1:Nn-1)-ItoHermiteMean).^2.*ZProb(wnStart+1:Nn-1)) 
disp('true Mean only applicble to standard SV mean reverting type models otherwise disregard');
TrueMean=theta+(x0-theta)*exp(-kappa*dt*Tt)%Mean reverting SDE original variable true average

MaxCutOff=30;
NoOfBins=round(300*gamma^2*4*sigma0/sqrt(MCMean)/(1+kappa));%Decrease the number of bins if the graph is too 
[YDensity,IndexOutY,IndexMaxY] = MakeDensityFromSimulation_Infiniti_NEW(YY,paths,NoOfBins,MaxCutOff );

%plot(y_w1(wnStart+1:Nn-1),py_w1(wnStart+1:Nn-1),'b',y_w(wnStart+1:Nn-1),py_w(wnStart+1:Nn-1),'r',IndexOutY(1:IndexMaxY),YDensity(1:IndexMaxY),'g');
%plot(y_w(wnStart+1:Nn-1),py_w(wnStart+1:Nn-1),'r',IndexOutY(1:IndexMaxY),YDensity(1:IndexMaxY),'g');
plot(y_w(wnStart+1:Nn-1),py_w(wnStart+1:Nn-1),'r',y_w1(wnStart+1:Nn-1),py_w1(wnStart+1:Nn-1),'b',IndexOutY(1:IndexMaxY),YDensity(1:IndexMaxY),'g');

title(sprintf('x0 = %.4f,theta=%.3f,kappa=%.2f,gamma=%.3f,sigma=%.2f,T=%.2f,dt=%.5f,M=%.4f,TM=%.4f', x0,theta,kappa,gamma,sigma0,T,dt,ItoHermiteMean,TrueMean));%,sprintf('theta= %f', theta), sprintf('kappa = %f', kappa),sprintf('sigma = %f', sigma0),sprintf('T = %f', T));
 
legend({'Improvised terms Model Density','Monte Carlo Density'},'Location','northeast')
 
str=input('red line is density of SDE from Ito-Hermite method, green is monte carlo.');
end
.
.
Here is the new version of some other functions.
.
function [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(Bn,sigma0,Bm0,Bm1,Bm2,dPm,pm0,dpm0,d2pm0,d3pm0,d4pm0,d5pm0)

%This function calculates CDF Pmn, PDF pmn, first derivative of Pdf dpmn,
%second derivative of PDF d2pmn, and third derivative of PDF d3pmn at an
%arbitrary point Bn on next time level grid. All these CDF, PDF and their
%derivatives are calculated from an entire subdivision Bm at time t grid.
%Bm1 and Bm2 are boundaries of grid cell Bm and Bm0 is center of grid cell
%Bm. 
% sigma0 is the volatility associated with transition gaussian originating
% from the center of grid Bm given as Bm0.
%dPm is the integrate probability mass in mth originating subdivision.
%pm0 is the value of probability distribution at the center of mth cell at 
%Bm0.
%dpm0 is the value of first derivative of probability distribution at the
%center of mth subdivision at Bm0;
%and so on for d2pm0(second derivative of pdf at Bm0), d3pm0, d4pm0, d5pm0.
%pdf and all its derivatives at center of mth subdivsion Bm0 are input to
%the function.
%This program is not written with regard to efficiency at all and I will
%optimize the final version for efficiency.

Bt=Bn-Bm0;
Zt=(Bn-Bm0)/sigma0;
Zt2=Zt^2;
Zt3=Zt^3;
Zt4=Zt^4;
Zt5=Zt^5;
Zt6=Zt^6;
Zt7=Zt^7;
Zt8=Zt^8;
cc1=sigma0;
cc2=sigma0^2;
cc3=sigma0^3;
cc4=sigma0^4;
cc5=sigma0^5;
cc6=sigma0^6;
cc7=sigma0^7;
cc8=sigma0^8;

Pm0n=normcdf(Bt,0,cc1);
dPm0ndZt=normpdf(Bt,0,cc1);
pm0n=normpdf(Bt,0,cc1);
d2Pm0ndZt2=-pm0n*(Zt)./cc1;
d3Pm0ndZt3=pm0n*(Zt2-1)./cc2;
d4Pm0ndZt4=-pm0n*(Zt3-3*Zt)./cc3;
d5Pm0ndZt5=pm0n*(Zt4-6*Zt2+3)./cc4;
d6Pm0ndZt6=-pm0n*(Zt5-10*Zt3+15*Zt)./cc5;
d7Pm0ndZt7=pm0n*(Zt6-15*Zt4+45*Zt2-15)./cc6;
d8Pm0ndZt8=-pm0n*(Zt7-21*Zt5+105*Zt3-105*Zt)/cc7;                      
d9Pm0ndZt9=pm0n*(Zt8-28*Zt6+210*Zt4-420*Zt2+105)./cc8;

%dBmdZt=-1;
dZtdBm=-1;

Zm1=Bn-(Bm1);
Zm2=Bn-(Bm2);

dBm=Bm2-Bm1;
%dBm1 is not needed.
dBm2=1/3* ((Bm2 - Bm0)^3 - (Bm1 - Bm0)^3)/2;
dBm3=1/4* ((Bm2 - Bm0)^4 - (Bm1 - Bm0)^4)/6;
dBm4=1/5* ((Bm2 - Bm0)^5 - (Bm1 - Bm0)^5)/24;
dBm5=1/6* ((Bm2 - Bm0)^6 - (Bm1 - Bm0)^6)/120;
dBm6=1/7* ((Bm2 - Bm0)^7 - (Bm1 - Bm0)^7)/720;

%Below are calculations for CDF at the target point Bn on next grid with respect to entire mth grid cell.
Integral1=(0.398942* exp(-((0.5* Zm1^2)/sigma0^2)) - 0.398942* exp(-((0.5* Zm2^2)/sigma0^2)))*sigma0;%Integral of Zp(Z)dZ term in by parts integration in G2.
Integral2=-Bn*(normcdf(Zm2,0,sigma0)-normcdf(Zm1,0,sigma0));    %Integral of p(Z)dZ term multiplied by -Bn in G2. 
Integral3=Bm2*normcdf(Zm2,0,sigma0)-Bm1*normcdf(Zm1,0,sigma0);  %The boundaries integral in by parts integration in G2.

Integral0=dPm.*Pm0n; % G1 group of terms in wilmott explanation.

IntegralCDF=Integral0+ ...  %Integral0 is Group1(G1) in the explanation on wilmott.
     pm0.*(+Integral1+Integral2+Integral3)-  Pm0n*pm0*dBm+ ... %This line is group2 or G2 in explanation.
     + 2* dpm0 * (dPm0ndZt*dZtdBm) *dBm2 + ...  %This line and lines below are G3 in explanation.
    + (3*d2pm0*(dPm0ndZt*dZtdBm) + 3*dpm0*(d2Pm0ndZt2*dZtdBm^2))*dBm3 + ...
    + (4*d3pm0*(dPm0ndZt*dZtdBm) + 6* d2pm0*(d2Pm0ndZt2*dZtdBm^2) + 4* dpm0 * (d3Pm0ndZt3*dZtdBm^3))*dBm4 + ...
    + (5*d4pm0*(dPm0ndZt*dZtdBm) + 10* d3pm0*(d2Pm0ndZt2*dZtdBm^2)+ 10* d2pm0*(d3Pm0ndZt3*dZtdBm^3) + 5* dpm0 * (d4Pm0ndZt4*dZtdBm^4))*dBm5 + ...
    + (6*d5pm0*(dPm0ndZt*dZtdBm) + 15* d4pm0*(d2Pm0ndZt2*dZtdBm^2)+ 20* d3pm0*(d3Pm0ndZt3*dZtdBm^3) + 15* d2pm0 * (d4Pm0ndZt4*dZtdBm^4)+ ...
    6* dpm0 * (d5Pm0ndZt5*dZtdBm^5)) * dBm6;

%I have multiplied derivatives w.r.t Zt with powers of dZtdBm in order to
%convert them to derivatives w.r.t Bm. Some of this is very inefficient and
%will change in next version.

%Below are calculations for PDF at the target point Bn on next grid with respect to entire mth grid cell.
%In all of the calculations below integrals ending with 1,2,3 as
%P1Integral1,P1Integral2 and P1Integral3 belong to by parts integration in
%group G2. And Integrals ending with 0 as in P1Integral0 belong to group
%G1.
P1Integral1=-(1/sigma0)*0.398942* ( exp(-((0.5* Zm1^2)/sigma0^2))* Zm1- ...
    exp(-((0.5* Zm2^2)/sigma0^2))* Zm2- ...
    1.25331* sigma0* erf((0.707107 *Zm1)/sigma0)+1.25331* sigma0* erf((0.707107 *Zm2)/sigma0));
P1Integral2=-Bn*(normpdf(Zm2,0,sigma0)-normpdf(Zm1,0,sigma0));
P1Integral3=Bm2*normpdf(Zm2,0,sigma0)-Bm1*normpdf(Zm1,0,sigma0);
P1Integral0=dPm.*pm0n;
IntegralD1CDF=P1Integral0+ ...  %Group G1 integral for PDF
    pm0.*(P1Integral1+P1Integral2+P1Integral3)-  pm0n*pm0*dBm + ... %Group G2 integrals for PDF.
    2* dpm0 * (d2Pm0ndZt2*dZtdBm) *dBm2 + ...     %Group G3 terms in this line and below.
    +(3*d2pm0*(d2Pm0ndZt2*dZtdBm) + 3*dpm0*(d3Pm0ndZt3*dZtdBm^2))*dBm3 + ...
    +(4*d3pm0*(d2Pm0ndZt2*dZtdBm) + 6* d2pm0*(d3Pm0ndZt3*dZtdBm^2) + 4* dpm0 * (d4Pm0ndZt4*dZtdBm^3))*dBm4 + ...
    + (5*d4pm0*(d2Pm0ndZt2*dZtdBm) + 10* d3pm0*(d3Pm0ndZt3*dZtdBm^2)+ 10* (d4Pm0ndZt4*dZtdBm^3) + 5* dpm0 * (d5Pm0ndZt5*dZtdBm^4))*dBm5 + ...
    + (6*d5pm0*(d2Pm0ndZt2*dZtdBm) + 15* d4pm0*(d3Pm0ndZt3*dZtdBm^2)+ 20* (d4Pm0ndZt4*dZtdBm^3) + 15* d2pm0 * (d5Pm0ndZt5*dZtdBm^4)+ 6* dpm0 * (d6Pm0ndZt6*dZtdBm^5)) * dBm6;

%Below are calculations for first derivative of PDF at the target point Bn on next time grid with respect to entire mth grid cell.

%P2Integral1=(1/((sigma0)^3)).*exp((-0.5* Zm1^2-0.5* Zm2^2)/sigma0^2).* (exp((0.5* Zm2^2)/sigma0^2)* (0.398942* sigma0^2+0.398942* Zm1^2)+...
%    exp((0.5* Zm1^2)/sigma0^2)* (-0.398942* sigma0^2 - 0.398942* Zm2^2));
P2Integral1=(1/((sigma0)^3)).* (exp((-0.5* Zm1^2)/sigma0^2)* (0.398942* sigma0^2+0.398942* Zm1^2)+...
    exp((-0.5* Zm2^2)/sigma0^2)* (-0.398942* sigma0^2 - 0.398942* Zm2^2));


%P2Integral1=(1/((sigma0^3)^(3/2)))E^((-0.5 Zm1^2-0.5 Zm2^2)/sigma^2) (E^((-0.5 Zm1^2)/sigma^2) (0.398942 sigma^2+0.398942 Zm1^2)+ ...
%    E^((-0.5 Zm2^2)/sigma^2) (-0.398942 sigma^2-0.398942 Zm2^2))

P2Integral2=-Bn*(-Zm2/sigma0/sigma0*normpdf(Zm2,0,sigma0)-(-Zm1)/sigma0^2*normpdf(Zm1,0,sigma0));
P2Integral3=Bm2*-Zm2/sigma0/sigma0*normpdf(Zm2,0,sigma0)-Bm1*(-Zm1)/sigma0^2*normpdf(Zm1,0,sigma0);
%PPIntegral0=dPm.*dpm0n;
P2Integral0=dPm.*d2Pm0ndZt2;
IntegralD2CDF=P2Integral0+ ... % Group G1 integral for first derivative of PDF
    pm0 * (P2Integral1+P2Integral2+P2Integral3)-  (d2Pm0ndZt2)*pm0*dBm+ ... %Group G2 integral terms for first derivative of PDF
    + (2* dpm0 * (d3Pm0ndZt3*dZtdBm)) *dBm2 + ...  %Group G3 terms in this line and below
    + (3*d2pm0*(d3Pm0ndZt3*dZtdBm) + 3*dpm0*(d4Pm0ndZt4*dZtdBm^2))*dBm3 + ...
    + (4*d3pm0*(d3Pm0ndZt3*dZtdBm) + 6* d2pm0*(d4Pm0ndZt4*dZtdBm^2) + 4* dpm0 * (d5Pm0ndZt5*dZtdBm^3))*dBm4 + ...
    + (5*d4pm0*(d3Pm0ndZt3*dZtdBm) + 10* d3pm0*(d4Pm0ndZt4*dZtdBm^2)+ 10* d2pm0*(d5Pm0ndZt5*dZtdBm^3) + 5* dpm0 * (d6Pm0ndZt6*dZtdBm^4))*dBm5 + ...
    + (6*d5pm0*(d3Pm0ndZt3*dZtdBm) + 15* d4pm0*(d4Pm0ndZt4*dZtdBm^2)+ 20* d3pm0*(d5Pm0ndZt5*dZtdBm^3) + 15* d2pm0 * (d6Pm0ndZt6*dZtdBm^4)+ 6* dpm0 * (d7Pm0ndZt7*dZtdBm^5)) * dBm6;

%Below are calculations for second derivative of PDF at the target point Bn on next time grid with respect to entire mth grid cell.

P3Integral1=(1/(sigma0^6))*sigma0* (-0.398942* exp(-((0.5* Zm1^2)/sigma0^2))* Zm1^3+  ...
    0.398942* exp(-((0.5* Zm2^2)/sigma0^2))* Zm2^3+sigma0^3 *(1.5* erf((0.707107* Zm1)/sigma0)- ...
    1.5* erf((0.707107* Zm1)/sigma0)-1.5* erf((0.707107* Zm2)/sigma0)+ ...
    1.5* erf((0.707107* Zm2)/sigma0)));
P3Integral2=-Bn*(((Zm2/sigma0)^2-1)/sigma0^2*normpdf(Zm2,0,sigma0)-((Zm1/sigma0)^2-1)/sigma0^2*normpdf(Zm1,0,sigma0));
P3Integral3=Bm2*((Zm2/sigma0)^2-1)/sigma0^2*normpdf(Zm2,0,sigma0)-Bm1*((Zm1/sigma0)^2-1)/sigma0^2*normpdf(Zm1,0,sigma0);
P3Integral0=dPm.*d3Pm0ndZt3;

IntegralD3CDF=P3Integral0+ ... %G1 integral for d2pdf
    pm0 * (P3Integral1+P3Integral2+P3Integral3)-  (d3Pm0ndZt3)*pm0*dBm+ ... %Group G2 terms for d2pdf
    + (2* dpm0 * (d4Pm0ndZt4*dZtdBm)) *dBm2 + ...  %G3 terms below
    + (3*d2pm0*(d4Pm0ndZt4*dZtdBm) + 3*dpm0*(d5Pm0ndZt5*dZtdBm^2))*dBm3 + ...
    + (4*d3pm0*(d4Pm0ndZt4*dZtdBm) + 6* d2pm0*(d5Pm0ndZt5*dZtdBm^2) + 4* dpm0 * (d6Pm0ndZt6*dZtdBm^3))*dBm4 + ...
    + (5*d4pm0*(d4Pm0ndZt4*dZtdBm) + 10* d3pm0*(d5Pm0ndZt5*dZtdBm^2)+ 10* d2pm0*(d6Pm0ndZt6*dZtdBm^3) + 5* dpm0 * (d7Pm0ndZt7*dZtdBm^4))*dBm5 + ...
    + (6*d5pm0*(d4Pm0ndZt4*dZtdBm) + 15* d4pm0*(d5Pm0ndZt5*dZtdBm^2)+ 20* d3pm0*(d6Pm0ndZt6*dZtdBm^3) + 15* d2pm0 * (d7Pm0ndZt7*dZtdBm^4)+ 6* dpm0 * (d8Pm0ndZt8*dZtdBm^5)) * dBm6;


%Below are calculations for third derivative of PDF at the target point Bn on next time grid with respect to entire mth grid cell.

P4Integral1=(1/(sigma0^8* sigma0))*(exp(-((0.5* Zm1^2)/sigma0^2))* (-0.398942* sigma0^6-0.797885* sigma0^4* Zm1^2+ ...
    0.398942* sigma0^2* Zm1^4)+exp(-((0.5* Zm2^2)/sigma0^2))* (0.398942* sigma0^6+0.797885* sigma0^4* Zm2^2-0.398942* sigma0^2* Zm2^4));
P4Integral2=-Bn*(((Zm2/sigma0)^3-3*(Zm2/sigma0))/sigma0^3*normpdf(Zm2,0,sigma0)-((Zm1/sigma0)^3-3*(Zm1/sigma0))/sigma0^3*normpdf(Zm1,0,sigma0));
P4Integral3=Bm2*((Zm2/sigma0)^3-3*(Zm2/sigma0))/sigma0^3*normpdf(Zm2,0,sigma0)-Bm1*((Zm1/sigma0)^3-3*(Zm1/sigma0))/sigma0^3*normpdf(Zm1,0,sigma0);
P4Integral0=dPm.*d4Pm0ndZt4;

IntegralD4CDF=P4Integral0+ ... %Group G1 terms for d3pdf 
    pm0 * (P4Integral1+P4Integral2+P4Integral3)-  (d4Pm0ndZt4)*pm0*dBm+ ...%Group G2 terms for d3pdf
    + (2* dpm0 * (d5Pm0ndZt5*dZtdBm)) *dBm2 + ...  %Group G3 terms for d3pdf
    + (3*d2pm0*(d5Pm0ndZt5*dZtdBm) + 3*dpm0*(d6Pm0ndZt6*dZtdBm^2))*dBm3 + ...
    + (4*d3pm0*(d5Pm0ndZt5*dZtdBm) + 6* d2pm0*(d6Pm0ndZt6*dZtdBm^2) + 4* dpm0 * (d7Pm0ndZt7*dZtdBm^3))*dBm4 + ...
    + (5*d4pm0*(d5Pm0ndZt5*dZtdBm) + 10* d3pm0*(d6Pm0ndZt6*dZtdBm^2)+ 10* d2pm0*(d7Pm0ndZt7*dZtdBm^3) + 5* dpm0 * (d8Pm0ndZt8*dZtdBm^4))*dBm5 + ...
    + (6*d5pm0*(d5Pm0ndZt5*dZtdBm) + 15* d4pm0*(d6Pm0ndZt6*dZtdBm^2)+ 20* d3pm0*(d7Pm0ndZt7*dZtdBm^3) + 15* d2pm0 * (d8Pm0ndZt8*dZtdBm^4)+ 6* dpm0 * (d9Pm0ndZt9*dZtdBm^5)) * dBm6;

Pmn=IntegralCDF;
pmn=IntegralD1CDF;
dpmn=IntegralD2CDF;
d2pmn=IntegralD3CDF;
d3pmn=IntegralD4CDF;

end
.
.
.
function [Pmn] = CalculateCDFFromSubDiv(Bn,sigma0,Bm0,Bm1,Bm2,dPm,pm0,dpm0,d2pm0,d3pm0,d4pm0,d5pm0)

%function [Pmn,pmn,dpmn] = CalculateCDFAndDerivativesFromSubDiv(Bn,sigma0,Bm0,Bm1,Bm2,Zm,dNn,dPm,Pm0,pm0,dpm0,d2pm0,d3pm0,dZdBm0,d2ZdB2m0,d3ZdB3m0)
 
%sort out B2a and B2b below.
%sigma0=cc1;
Zm1=Bn-(Bm1);
Zm2=Bn-(Bm2);



dBm=Bm2-Bm1;
dBm2=1/3* ((Bm2 - Bm0)^3 - (Bm1 - Bm0)^3)/2;
dBm3=1/4* ((Bm2 - Bm0)^4 - (Bm1 - Bm0)^4)/6;
dBm4=1/5* ((Bm2 - Bm0)^5 - (Bm1 - Bm0)^5)/24;
dBm5=1/6* ((Bm2 - Bm0)^6 - (Bm1 - Bm0)^6)/120;
dBm6=1/7* ((Bm2 - Bm0)^7 - (Bm1 - Bm0)^7)/720;

%IntegralCDF=Integral0+  pm0.*(+Integral21+Integral22+Integral1)-  Pm0n*pm0*dBm + 2* dpm0 * pm0n *dBm2 + ...
%    + (3*d2pm0*pm0n + 3*dpm0*dpm0n)*dBm3 + ...
%    + (4*d3pm0*pm0n + 6* d2pm0*dpm0n + 4* dpm0 * d2pm0n)*dBm4 + ...
%    + (5*d4pm0*dpm0n + 10* d3pm0*dpm0n+ 10* d2pm0*d2pm0n + 5* dpm0 * d3pm0n)*dBm5 + ...
%    + (6*d5pm0*dpm0n + 15* d4pm0*dpm0n+ 20* d3pm0*d2pm0n + 15* d2pm0 * d3pm0n+ 6* dpm0 * d4pm0n) * dBm6;

%Pmn=IntegralCDF;

Bt=Bn-Bm0;
Zt=(Bn-Bm0)/sigma0;
Zt2=Zt^2;
Zt3=Zt^3;
Zt4=Zt^4;
Zt5=Zt^5;
Zt6=Zt^6;
Zt7=Zt^7;
Zt8=Zt^8;
cc1=sigma0;
cc2=sigma0^2;
cc3=sigma0^3;
cc4=sigma0^4;
cc5=sigma0^5;
cc6=sigma0^6;
cc7=sigma0^7;
cc8=sigma0^8;




Pm0n=normcdf(Bt,0,cc1);
pm0n=normpdf(Bt,0,cc1);
dPm0ndZt=normpdf(Bt,0,cc1);
d2Pm0ndZt2=-pm0n*(Zt)./cc1;
d3Pm0ndZt3=pm0n*(Zt2-1)./cc2;
d4Pm0ndZt4=-pm0n*(Zt3-3*Zt)./cc3;
d5Pm0ndZt5=pm0n*(Zt4-6*Zt2+3)./cc4;
d6Pm0ndZt6=-pm0n*(Zt5-10*Zt3+15*Zt)./cc5;
d7Pm0ndZt7=pm0n*(Zt6-15*Zt4+45*Zt2-15)./cc6;
d8Pm0ndZt8=-pm0n*(Zt7-21*Zt5+105*Zt3-105*Zt)/cc7;                      
d9Pm0ndZt9=pm0n*(Zt8-28*Zt6+210*Zt4-420*Zt2+105)./cc8;

Integral21=(0.398942* exp(-((0.5* Zm1^2)/sigma0^2)) - 0.398942* exp(-((0.5* Zm2^2)/sigma0^2)))*sigma0;
Integral22=-Bn*(normcdf(Zm2,0,sigma0)-normcdf(Zm1,0,sigma0));
Integral1=Bm2*normcdf(Zm2,0,sigma0)-Bm1*normcdf(Zm1,0,sigma0);
Integral0=dPm.*Pm0n;



dBmdZt=-1;

IntegralCDF=Integral0+  pm0.*(+Integral21+Integral22+Integral1)-  Pm0n*pm0*dBm + 2* dpm0 * (dPm0ndZt*dBmdZt) *dBm2 + ...
    + (3*d2pm0*(dPm0ndZt*dBmdZt) + 3*dpm0*(d2Pm0ndZt2*dBmdZt^2))*dBm3 + ...
    + (4*d3pm0*(dPm0ndZt*dBmdZt) + 6* d2pm0*(d2Pm0ndZt2*dBmdZt^2) + 4* dpm0 * (d3Pm0ndZt3*dBmdZt^3))*dBm4 + ...
    + (5*d4pm0*(dPm0ndZt*dBmdZt) + 10* d3pm0*(d2Pm0ndZt2*dBmdZt^2)+ 10* d2pm0*(d3Pm0ndZt3*dBmdZt^3) + 5* dpm0 * (d4Pm0ndZt4*dBmdZt^4))*dBm5 + ...
    + (6*d5pm0*(dPm0ndZt*dBmdZt) + 15* d4pm0*(d2Pm0ndZt2*dBmdZt^2)+ 20* d3pm0*(d3Pm0ndZt3*dBmdZt^3) + 15* d2pm0 * (d4Pm0ndZt4*dBmdZt^4)+ ...
    6* dpm0 * (d5Pm0ndZt5*dBmdZt^5)) * dBm6;


Pmn=IntegralCDF;



end
.
.
.
function [dB] =SolveQuarticRootForProb(ExcessCDF,pout,dpoutdB,d2poutdB2,d3poutdB3,DirectionFlag)
%ChooseQuadraticRoot(dB1,dB2,ExcessCDF,pout(nn),dpoutdB(nn),DirectionFlag)
             
if(DirectionFlag==1)
    if(ExcessCDF>0)

        a0=1/24*d3poutdB3;
        b0=1/6*d2poutdB2;
        c0=1/2*dpoutdB;
        d0=pout;
        e0=ExcessCDF;
        
        [dB1,dB2,dB3,dB4] =SolveQuarticRootMathematica(a0,b0,c0,d0,e0);

        dB0=-ExcessCDF/pout;
%         dB1
%         dB2
%         dB3
%         dB4
%         dB0
%         
%         a0*dB1^4+b0*dB1^3+c0*dB1^2+d0*dB1+e0
%         a0*dB2^4+b0*dB2^3+c0*dB2^2+d0*dB2+e0
%         a0*dB3^4+b0*dB3^3+c0*dB3^2+d0*dB3+e0
%         a0*dB4^4+b0*dB4^3+c0*dB4^2+d0*dB4+e0
%         
        
        Bdiff=10000;
        if(dB1<0)
            Bdiff=abs(dB1-dB0);
            dB=dB1;
        end
        if((dB2<0)&&(abs(dB2-dB0)<Bdiff))
            Bdiff=abs(dB2-dB0);
            dB=dB2;
        end
        if((dB3<0)&&(abs(dB3-dB0)<Bdiff))
            Bdiff=abs(dB3-dB0);
            dB=dB3;
        end
        if((dB4<0)&&(abs(dB4-dB0)<Bdiff))
            Bdiff=abs(dB4-dB0);
            dB=dB4;
        end

    elseif(ExcessCDF<0)
        
        a0=1/24*d3poutdB3;
        b0=1/6*d2poutdB2;
        c0=1/2*dpoutdB;
        d0=pout;
        e0=ExcessCDF;
        
        [dB1,dB2,dB3,dB4] =SolveQuarticRootMathematica(a0,b0,c0,d0,e0);

        dB0=-ExcessCDF/pout;

%         dB1
%         dB2
%         dB3
%         dB4
%         dB0
%         
%         a0*dB1^4+b0*dB1^3+c0*dB1^2+d0*dB1+e0
%         a0*dB2^4+b0*dB2^3+c0*dB2^2+d0*dB2+e0
%         a0*dB3^4+b0*dB3^3+c0*dB3^2+d0*dB3+e0
%         a0*dB4^4+b0*dB4^3+c0*dB4^2+d0*dB4+e0
%         
        
        
        Bdiff=10000;
        if(dB1>0)
            Bdiff=abs(dB1-dB0);
            dB=dB1;
        end
        if((dB2>0)&&(abs(dB2-dB0)<Bdiff))
            Bdiff=abs(dB2-dB0);
            dB=dB2;
        end
        if((dB3>0)&&(abs(dB3-dB0)<Bdiff))
            Bdiff=abs(dB3-dB0);
            dB=dB3;
        end
        if((dB4>0)&&(abs(dB4-dB0)<Bdiff))
            Bdiff=abs(dB4-dB0);
            dB=dB4;
        end
    end
end
if(DirectionFlag==-1)
    if(ExcessCDF>0)

        %a0=1/2*dpoutdB;
        %b0=pout;
        %c0=-ExcessCDF;

        a0=1/24*d3poutdB3;
        b0=1/6*d2poutdB2;
        c0=1/2*dpoutdB;
        d0=pout;
        e0=-ExcessCDF;
        
        [dB1,dB2,dB3,dB4] =SolveQuarticRootMathematica(a0,b0,c0,d0,e0);

        dB0=ExcessCDF/pout;
        
%         dB1
%         dB2
%         dB3
%         dB4
%         dB0
%         
%         a0*dB1^4+b0*dB1^3+c0*dB1^2+d0*dB1+e0
%         a0*dB2^4+b0*dB2^3+c0*dB2^2+d0*dB2+e0
%         a0*dB3^4+b0*dB3^3+c0*dB3^2+d0*dB3+e0
%         a0*dB4^4+b0*dB4^3+c0*dB4^2+d0*dB4+e0

        
        Bdiff=10000;
        if(dB1>0)
            Bdiff=abs(dB1-dB0);
            dB=dB1;
        end
        if((dB2>0)&&(abs(dB2-dB0)<Bdiff))
            Bdiff=abs(dB2-dB0);
            dB=dB2;
        end
        if((dB3>0)&&(abs(dB3-dB0)<Bdiff))
            Bdiff=abs(dB3-dB0);
            dB=dB3;
        end
        if((dB4>0)&&(abs(dB4-dB0)<Bdiff))
            Bdiff=abs(dB4-dB0);
            dB=dB4;
        end
    elseif(ExcessCDF<0)

    %    a0=1/2*dpoutdB;
    %    b0=-pout;
    %    c0=ExcessCDF;
        
        
        a0=1/24*d3poutdB3;
        b0=1/6*d2poutdB2;
        c0=1/2*dpoutdB;
        d0=pout;
        e0=-ExcessCDF;
        
        [dB1,dB2,dB3,dB4] =SolveQuarticRootMathematica(a0,b0,c0,d0,e0);
    
        dB0=ExcessCDF/pout;
        
%         a0
%         b0
%         c0
%         d0
%         e0
% 
%         dB1
%         dB2
%         dB3
%         dB4
        Bdiff=10000;
        if(dB1<0)
            Bdiff=abs(dB1-dB0);
            dB=dB1;
        end
        if((dB2<0)&&(abs(dB2-dB0)<Bdiff))
            Bdiff=abs(dB2-dB0);
            dB=dB2;
        end
        if((dB3<0)&&(abs(dB3-dB0)<Bdiff))
            Bdiff=abs(dB3-dB0);
            dB=dB3;
        end
        if((dB4<0)&&(abs(dB4-dB0)<Bdiff))
            Bdiff=abs(dB4-dB0);
            dB=dB4;
        end
    end
end

.
.
.
function [wMu0dt,c1,c2] = CalculateDriftAndVolA8Trans(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt)

yy(wnStart:Nn)=((1-gamma)*w(wnStart:Nn)).^(1/(1-gamma));

%Fp2=Fp1/(1-gamma);

wMu0dt(wnStart:Nn)=(YqCoeff0(1,1,2,1).*yy(wnStart:Nn).^Fp1(1,1,2,1)+ ...
    YqCoeff0(1,2,1,1).*yy(wnStart:Nn).^Fp1(1,2,1,1)+ ...
    YqCoeff0(2,1,1,1).*yy(wnStart:Nn).^Fp1(2,1,1,1))*dt + ...
    (YqCoeff0(1,1,3,1).*yy(wnStart:Nn).^Fp1(1,1,3,1)+ ...
    YqCoeff0(1,2,2,1).*yy(wnStart:Nn).^Fp1(1,2,2,1)+ ...
    YqCoeff0(2,1,2,1).*yy(wnStart:Nn).^Fp1(2,1,2,1)+ ...
    YqCoeff0(1,3,1,1).*yy(wnStart:Nn).^Fp1(1,3,1,1)+ ...
    YqCoeff0(2,2,1,1).*yy(wnStart:Nn).^Fp1(2,2,1,1)+ ...
    YqCoeff0(3,1,1,1).*yy(wnStart:Nn).^Fp1(3,1,1,1))*dt^2 + ...
     (YqCoeff0(1,1,4,1).*yy(wnStart:Nn).^Fp1(1,1,4,1)+ ...
     YqCoeff0(1,2,3,1).*yy(wnStart:Nn).^Fp1(1,2,3,1)+ ...
     YqCoeff0(2,1,3,1).*yy(wnStart:Nn).^Fp1(2,1,3,1)+ ...
     YqCoeff0(1,3,2,1).*yy(wnStart:Nn).^Fp1(1,3,2,1)+ ...
     YqCoeff0(2,2,2,1).*yy(wnStart:Nn).^Fp1(2,2,2,1)+ ...
     YqCoeff0(3,1,2,1).*yy(wnStart:Nn).^Fp1(3,1,2,1)+ ...
     YqCoeff0(1,4,1,1).*yy(wnStart:Nn).^Fp1(1,4,1,1)+ ...
     YqCoeff0(2,3,1,1).*yy(wnStart:Nn).^Fp1(2,3,1,1)+ ...
     YqCoeff0(3,2,1,1).*yy(wnStart:Nn).^Fp1(3,2,1,1)+ ...
     YqCoeff0(4,1,1,1).*yy(wnStart:Nn).^Fp1(4,1,1,1))*dt^3;%+ ...
%      (YqCoeff0(1,1,5,1).*yy(wnStart:Nn).^Fp1(1,1,5,1)+ ...
%       YqCoeff0(1,2,4,1).*yy(wnStart:Nn).^Fp1(1,2,4,1)+ ...
%       YqCoeff0(2,1,4,1).*yy(wnStart:Nn).^Fp1(2,1,4,1)+ ...
%       YqCoeff0(2,1,1,1).*yy(wnStart:Nn).^Fp1(2,1,1,1)+ ...
%        YqCoeff0(2,2,3,1).*yy(wnStart:Nn).^Fp1(2,2,3,1)+ ...
%        YqCoeff0(3,1,3,1).*yy(wnStart:Nn).^Fp1(3,1,3,1)+ ...
%        YqCoeff0(1,4,2,1).*yy(wnStart:Nn).^Fp1(1,4,2,1)+ ...
%        YqCoeff0(2,3,2,1).*yy(wnStart:Nn).^Fp1(2,3,2,1)+ ...
%        YqCoeff0(3,2,2,1).*yy(wnStart:Nn).^Fp1(3,2,2,1)+ ...
%        YqCoeff0(4,1,2,1).*yy(wnStart:Nn).^Fp1(4,1,2,1)+ ...
%        YqCoeff0(1,5,1,1).*yy(wnStart:Nn).^Fp1(1,5,1,1)+ ...
%        YqCoeff0(2,4,1,1).*yy(wnStart:Nn).^Fp1(2,4,1,1)+ ...
%        YqCoeff0(3,3,1,1).*yy(wnStart:Nn).^Fp1(3,3,1,1)+  ...
%        YqCoeff0(4,2,1,1).*yy(wnStart:Nn).^Fp1(4,2,1,1)+ ...
%        YqCoeff0(5,1,1,1).*yy(wnStart:Nn).^Fp1(5,1,1,1))*dt^4;





%c1(wnStart:Nn)=YqCoeff0(1,1,1,2).*yy(wnStart:Nn).^Fp1(1,1,1,2).*sqrt(dt)+ ...
%    (YqCoeff0(1,1,2,2).*yy(wnStart:Nn).^Fp1(1,1,2,2)+YqCoeff0(1,2,1,2).*yy(wnStart:Nn).^Fp1(1,2,1,2)+ ...
%    YqCoeff0(2,1,1,2).*yy(wnStart:Nn).^Fp1(2,1,1,2)).*dt^1.5;%+ ...
 
c1(wnStart:Nn)=((YqCoeff0(1,1,1,2).*yy(wnStart:Nn).^Fp1(1,1,1,2).*sqrt(dt))+ ...
     (YqCoeff0(1,1,2,2).*yy(wnStart:Nn).^Fp1(1,1,2,2)+YqCoeff0(1,2,1,2).*yy(wnStart:Nn).^Fp1(1,2,1,2)+ ...
     YqCoeff0(2,1,1,2).*yy(wnStart:Nn).^Fp1(2,1,1,2)).*dt^1.5+ ...
     (YqCoeff0(1,1,3,2).*yy(wnStart:Nn).^Fp1(1,1,3,2)+YqCoeff0(1,2,2,2).*yy(wnStart:Nn).^Fp1(1,2,2,2)+ ...
     YqCoeff0(2,1,2,2).*yy(wnStart:Nn).^Fp1(2,1,2,2)+YqCoeff0(1,3,1,2).*yy(wnStart:Nn).^Fp1(1,3,1,2)+ ...
     YqCoeff0(2,2,1,2).*yy(wnStart:Nn).^Fp1(2,2,1,2)+YqCoeff0(3,1,1,2).*yy(wnStart:Nn).^Fp1(3,1,1,2)).*dt^2.5+ ...
     (YqCoeff0(1,1,4,2).*yy(wnStart:Nn).^Fp1(1,1,4,2)+YqCoeff0(1,2,3,2).*yy(wnStart:Nn).^Fp1(1,2,3,2)+ ...
     YqCoeff0(2,1,3,2).*yy(wnStart:Nn).^Fp1(2,1,3,2)+YqCoeff0(1,3,2,2).*yy(wnStart:Nn).^Fp1(1,3,2,2)+ ...
     YqCoeff0(2,2,2,2).*yy(wnStart:Nn).^Fp1(2,2,2,2)+ YqCoeff0(3,1,2,2).*yy(wnStart:Nn).^Fp1(3,1,2,2)+ ...
     YqCoeff0(1,4,1,2).*yy(wnStart:Nn).^Fp1(1,4,1,2)+YqCoeff0(2,3,1,2).*yy(wnStart:Nn).^Fp1(2,3,1,2)+ ...
     YqCoeff0(3,2,1,2).*yy(wnStart:Nn).^Fp1(3,2,1,2)+YqCoeff0(4,1,1,2).*yy(wnStart:Nn).^Fp1(4,1,1,2)).*dt^3.5);


 c2(wnStart:Nn)=((YqCoeff0(1,1,1,3).*yy(wnStart:Nn).^Fp1(1,1,1,3) *dt) + ...
     (YqCoeff0(1,1,2,3).*yy(wnStart:Nn).^Fp1(1,1,2,3)+YqCoeff0(1,2,1,3).*yy(wnStart:Nn).^Fp1(1,2,1,3)+ ...
     YqCoeff0(2,1,1,3).*yy(wnStart:Nn).^Fp1(2,1,1,3)).*dt^2+ ...
     (YqCoeff0(1,1,3,3).*yy(wnStart:Nn).^Fp1(1,1,3,3)+YqCoeff0(1,2,2,3).*yy(wnStart:Nn).^Fp1(1,2,2,3)+ ...
     YqCoeff0(2,1,2,3).*yy(wnStart:Nn).^Fp1(2,1,2,3) + YqCoeff0(1,3,1,3).*yy(wnStart:Nn).^Fp1(1,3,1,3)+ ...
     YqCoeff0(2,2,1,3).*yy(wnStart:Nn).^Fp1(2,2,1,3)+YqCoeff0(3,1,1,3).*yy(wnStart:Nn).^Fp1(3,1,1,3)).*dt^3);

 
 
 
 
% 
% 
%    YY(1:paths)=YY(1:paths) + ...
%        (YCoeff0(1,1,2,1).*YY(1:paths).^Fp(1,1,2,1)+YCoeff0(1,2,1,1).*YY(1:paths).^Fp(1,2,1,1)+ ...
%        YCoeff0(2,1,1,1).*YY(1:paths).^Fp(2,1,1,1))*dtM + ...
%        (YCoeff0(1,1,3,1).*YY(1:paths).^Fp(1,1,3,1)+YCoeff0(1,2,2,1).*YY(1:paths).^Fp(1,2,2,1)+ ...
%        YCoeff0(2,1,2,1).*YY(1:paths).^Fp(2,1,2,1)+YCoeff0(1,3,1,1).*YY(1:paths).^Fp(1,3,1,1)+ ...
%        YCoeff0(2,2,1,1).*YY(1:paths).^Fp(2,2,1,1)+YCoeff0(3,1,1,1).*YY(1:paths).^Fp(3,1,1,1))*dtM^2 + ...
%        (YCoeff0(1,1,4,1).*YY(1:paths).^Fp(1,1,4,1)+YCoeff0(1,2,3,1).*YY(1:paths).^Fp(1,2,3,1)+ ...
%        YCoeff0(2,1,3,1).*YY(1:paths).^Fp(2,1,3,1)+YCoeff0(1,3,2,1).*YY(1:paths).^Fp(1,3,2,1)+ ...
%        YCoeff0(2,2,2,1).*YY(1:paths).^Fp(2,2,2,1)+YCoeff0(3,1,2,1).*YY(1:paths).^Fp(3,1,2,1)+ ...
%        YCoeff0(1,4,1,1).*YY(1:paths).^Fp(1,4,1,1)+YCoeff0(2,3,1,1).*YY(1:paths).^Fp(2,3,1,1)+ ...
%        YCoeff0(3,2,1,1).*YY(1:paths).^Fp(3,2,1,1)+YCoeff0(4,1,1,1).*YY(1:paths).^Fp(4,1,1,1))*dtM^3 + ...
%         (YCoeff0(1,1,5,1).*YY(1:paths).^Fp(1,1,5,1)+YCoeff0(1,2,4,1).*YY(1:paths).^Fp(1,2,4,1)+ ...
%      YCoeff0(2,1,4,1).*YY(1:paths).^Fp(2,1,4,1)+YCoeff0(2,1,1,1).*YY(1:paths).^Fp(2,1,1,1)+ ...
%       YCoeff0(2,2,3,1).*YY(1:paths).^Fp(2,2,3,1)+ ...
%       YCoeff0(3,1,3,1).*YY(1:paths).^Fp(3,1,3,1)+YCoeff0(1,4,2,1).*YY(1:paths).^Fp(1,4,2,1)+ ...
%       YCoeff0(2,3,2,1).*YY(1:paths).^Fp(2,3,2,1)+YCoeff0(3,2,2,1).*YY(1:paths).^Fp(3,2,2,1)+ ...
%       YCoeff0(4,1,2,1).*YY(1:paths).^Fp(4,1,2,1)+YCoeff0(1,5,1,1).*YY(1:paths).^Fp(1,5,1,1)+ ...
%       YCoeff0(2,4,1,1).*YY(1:paths).^Fp(2,4,1,1)+ ...
%       YCoeff0(3,3,1,1).*YY(1:paths).^Fp(3,3,1,1)+YCoeff0(4,2,1,1).*YY(1:paths).^Fp(4,2,1,1)+ ...
%       YCoeff0(5,1,1,1).*YY(1:paths).^Fp(5,1,1,1))*dtM^4+ ...
%        ((YCoeff0(1,1,1,2).*YY(1:paths).^Fp(1,1,1,2).*sqrt(dtM))+ ...
%      (YCoeff0(1,1,2,2).*YY(1:paths).^Fp(1,1,2,2)+YCoeff0(1,2,1,2).*YY(1:paths).^Fp(1,2,1,2)+ ...
%      YCoeff0(2,1,1,2).*YY(1:paths).^Fp(2,1,1,2)).*dtM^1.5+ ...
%      (YCoeff0(1,1,3,2).*YY(1:paths).^Fp(1,1,3,2)+YCoeff0(1,2,2,2).*YY(1:paths).^Fp(1,2,2,2)+ ...
%      YCoeff0(2,1,2,2).*YY(1:paths).^Fp(2,1,2,2)+YCoeff0(1,3,1,2).*YY(1:paths).^Fp(1,3,1,2)+ ...
%      YCoeff0(2,2,1,2).*YY(1:paths).^Fp(2,2,1,2)+YCoeff0(3,1,1,2).*YY(1:paths).^Fp(3,1,1,2)).*dtM^2.5+ ...
%      (YCoeff0(1,1,4,2).*YY(1:paths).^Fp(1,1,4,2)+YCoeff0(1,2,3,2).*YY(1:paths).^Fp(1,2,3,2)+ ...
%      YCoeff0(2,1,3,2).*YY(1:paths).^Fp(2,1,3,2)+YCoeff0(1,3,2,2).*YY(1:paths).^Fp(1,3,2,2)+ ...
%      YCoeff0(2,2,2,2).*YY(1:paths).^Fp(2,2,2,2)+ YCoeff0(3,1,2,2).*YY(1:paths).^Fp(3,1,2,2)+ ...
%      YCoeff0(1,4,1,2).*YY(1:paths).^Fp(1,4,1,2)+YCoeff0(2,3,1,2).*YY(1:paths).^Fp(2,3,1,2)+ ...
%      YCoeff0(3,2,1,2).*YY(1:paths).^Fp(3,2,1,2)+YCoeff0(4,1,1,2).*YY(1:paths).^Fp(4,1,1,2)).*dtM^3.5) .*HermiteP1(2,1:paths) + ...
%      ((YCoeff0(1,1,1,3).*YY(1:paths).^Fp(1,1,1,3) *dtM) + ...
%      (YCoeff0(1,1,2,3).*YY(1:paths).^Fp(1,1,2,3)+YCoeff0(1,2,1,3).*YY(1:paths).^Fp(1,2,1,3)+ ...
%      YCoeff0(2,1,1,3).*YY(1:paths).^Fp(2,1,1,3)).*dtM^2+ ...
%      (YCoeff0(1,1,3,3).*YY(1:paths).^Fp(1,1,3,3)+YCoeff0(1,2,2,3).*YY(1:paths).^Fp(1,2,2,3)+ ...
%      YCoeff0(2,1,2,3).*YY(1:paths).^Fp(2,1,2,3) + YCoeff0(1,3,1,3).*YY(1:paths).^Fp(1,3,1,3)+ ...
%      YCoeff0(2,2,1,3).*YY(1:paths).^Fp(2,2,1,3)+YCoeff0(3,1,1,3).*YY(1:paths).^Fp(3,1,1,3)).*dtM^3).*HermiteP1(3,1:paths) + ...





end
.
.
.
Here is the final output of the program.

ItoHermiteMean =
   0.131034250961208
true Mean only applicable to standard SV mean reverting type models otherwise disregard
TrueMean =
   0.131090903021946
Original process average from monte carlo
MCMean =
   0.131053978051384
MCVar =
   0.001423070749946
Original process average from our simulation
ItoHermiteMean =
   0.131034250961208
ItoHermiteVar =
   0.001411952818302
true Mean only applicble to standard SV mean reverting type models otherwise disregard
TrueMean =
   0.131090903021946
IndexMax =
   236
 
User avatar
Amin
Topic Author
Posts: 2730
Joined: July 14th, 2002, 3:00 am

Re: Breakthrough in the theory of stochastic differential equations and their simulation

March 10th, 2021, 6:15 pm

Very slightly modified version of the main function. Code output remains exactly the same we had in the last post. I checked it again.
function [] = SDETransProb08WmtGrid200b49()

%Copyright Ahsan Amin. Infiniti derivatives Technologies.
%Please fell free to connect on linkedin: linkedin.com/in/ahsan-amin-0a53334 
%or skype ahsan.amin2999
%In this program, I am simulating the SDE given as
%dy(t)=mu1 x(t)^beta1 dt + mu2 x(t)^beta2 dt +sigma x(t)^gamma dz(t)

%I have not directly simulated the SDE but simulated the transformed 
%Besse1 process version of the SDE and then changed coordinates to retreive
%the SDE in original coordinates.
%The present program will analytically evolve only the Bessel Process version of the
%SDE in transformed coordinates.

%In this program, I have simulated the density for first sixteen time
%intervals using a simple method. After first sixteen intervals, I start
%simulating with probability mass transfer method. I am presenting a
%simpler version which is easier to understand. I have advanced the density
%here for only two steps with mass transfer method. 17 to 18 intervals.
%My extrapolations at the boundaries are not very good and I suggest that
%you use your favorite method for that. Same for caclualtion of higher
%order derivatives. With above improvements, you can easily continue the
%method for whatever number of steps. Please experiment with step size and
%you will find the method robust enough. This is just an early version and
%I will be coming with better versions soon.

%In this mass transfer version, I have calculated centre of the distribution
%at time t+1 and then move to the right by assigning a trial boundary to each cell and
%then probability mass in each cell at time t+1 with trial boundary is
%calculated. The small defect in true probability mass and calculated
%probability mass is used with derivatives to calculate the exact boundary.
%Then we repeat the algorithm from left of zero towards -6 SD.
%The present version is a serial algorithm. A better algorithm would be a
%parallel algorithm that would simply assign a trial boundary and one CDF
%value associated with that trial boundary instead of calculating CDF on
%both boundaries and then equating probability mass in each cell serially.
%Since I started working with this version, I retained it but in next
%version, I will make it a cheaper algorithm that will be very simple to
%parallelize.

dt=.125/16/2/2/2;   % Simulation time interval.%Fodiffusions close to zero
             %decrease dt for accuracy.

%T=Tt*dt;
Tt=18;
T=Tt*dt;
OrderA=4;  %
dtM=dt;%.125/2/4;%Monte carlo time interval size dtM.
TtM=Tt;%T*2*8*4;%Monte carlo number of simulation intervals.



dNn=.05;   % Normal density subdivisions width. would change with number of subdivisions
Nn=200;  % No of normal density subdivisions
NnMidl=100;%One half density Subdivision left from mid of normal density(low)
NnMidh=101;%One half density subdivision right from the mid of normal density(high)
NnMid=4.0;

Z(1:Nn)=(((1:Nn)-20.5)*dNn-NnMid)

%There are two indices. One goes to Nn=200. This is used for calculation of
%SDE simulation at next time level t+1. This covers -5 to +5 SDs of
%underlying Z.
%Second index Nn1 below goes from 1 to 240. This covers -6 to +6 SD of
%underlying Z. In probability mass transfer methos, we simulate the SDE
%from -5 SD to +5 SD and then extrapolate on both sides so that we have a
%new grid from -6 SD to +6 SD(1:Nn1). This extrapolated grid(which is assigned time t)
%is used to calculate the time t+1 grid from -5 SD to +5 SD(1:Nn).
%Grid spacing is the same on both grids.
Nn1=240;
%dNn1=.05;
Nn1Midl=120;
Nn1Midh=121;
Nn1Mid=6.025;

Z1(1:Nn1)=((1:Nn1)*dNn-Nn1Mid)
Z1Prob(1)=normcdf(-5.95)-normcdf(-6.0);
Z1Prob(Nn1)=normcdf(6.0)-normcdf(5.95);
Z1Prob(2:Nn1-1)=normcdf(.5*Z1(2:Nn1-1)+.5*Z1(3:Nn1),0,1)-normcdf(.5*Z1(2:Nn1-1)+.5*Z1(1:Nn1-2),0,1);

ZProb(1:Nn)=Z1Prob(21:Nn1-20);
Z(1:Nn)=Z1(21:Nn1-20);


sum(Z1Prob(1:Nn1))
sum(ZProb(1:Nn))
str=input('Look at Zs');

x0=.100;   % starting value of SDE
beta1=0.0;
beta2=1.00;   % Second drift term power.
gamma=.5;%50;   % volatility power.                                                                                                                                                                                                                                                                     
kappa=2.0;%.950;   %mean reversion parameter.
theta=1.0;%mean reversion target
sigma0=.850;%Volatility value

%you can specify any general mu1 and mu2 and beta1 and beta2.
mu1=+1*theta*kappa;   %first drift coefficient.
mu2=-1*kappa;    % Second drift coefficient.
%mu1=0;
%mu2=0;

alpha=1;% x^alpha is being expanded. This is currently for monte carlo only.
alpha1=1-gamma;%This is for expansion of integrals for calculation of drift 
%and volatility coefficients
                
w(1:Nn)=x0^(1-gamma)/(1-gamma);

Z
Z1
str=input('Look at Zs');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

sigma11(1:OrderA+1)=0;
mu11(1:OrderA+1)=0;
mu22(1:OrderA+1)=0;
sigma22(1:OrderA+1)=0;
% index 1 correponds to zero level since matlab indexing starts at one. 
sigma11(1)=1;
mu11(1)=1;
mu22(1)=1;
sigma22(1)=1;


mu33(1)=1;
mu44(1)=1;
mu33(2:OrderA+1)=0;
mu44(2:OrderA+1)=0;

for k=1:(OrderA+1)
    if sigma0~=0
        sigma11(k)=sigma0^(k-1);
    end
    if mu1 ~= 0
        mu11(k)=mu1^(k-1);
    end
    if mu2 ~= 0
        mu22(k)=mu2^(k-1);
    end
    if sigma0~=0
        sigma22(k)=sigma0^(2*(k-1));
    end
end
%Ft(1:TtM+1,1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0; %General time powers on hermite polynomials
Fp(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;%General x powers on coefficients of hermite polynomials.
Fp1(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;%General x powers for bessel transformed coordinates.

%YCoeff0 and YCoeff are coefficents for original coordinates monte carlo.
%YqCoeff0 and YqCoeff are bessel/lamperti version monte carlo.

YCoeff0(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;
YqCoeff0(1:(OrderA+1),1:(OrderA+1),1:(OrderA+1),1:(OrderA+1))=0;
%Pre-compute the time and power exponent values in small multi-dimensional arrays
YCoeff = ItoTaylorCoeffsNew(alpha,beta1,beta2,gamma); %expand y^alpha where alpha=1;
YqCoeff = ItoTaylorCoeffsNew(alpha1,beta1,beta2,gamma);%expand y^alpha1 where alpha1=(1-gamma)
YqCoeff=YqCoeff/(1-gamma); %Transformed coordinates coefficients have to be 
%further divided by (1-gamma)

for k = 0 : (OrderA)
    for m = 0:k
        l4 = k - m + 1;
        for n = 0 : m
            l3 = m - n + 1;
            for j = 0:n
                l2 = n - j + 1;
                l1 = j + 1;
                %Ft(l1,l2,l3,l4) = dtM^((l1-1) + (l2-1) + (l3-1) + .5* (l4-1));
                Fp(l1,l2,l3,l4) = (alpha + (l1-1) * beta1 + (l2-1) * beta2 + (l3-1) * 2* gamma + (l4-1) * gamma ...
                    - (l1-1) - (l2-1) - 2* (l3-1) - (l4-1));
                Fp1(l1,l2,l3,l4) = (alpha1 + (l1-1) * beta1 + (l2-1) * beta2 + (l3-1) * 2* gamma + (l4-1) * gamma ...
                    - (l1-1) - (l2-1) - 2* (l3-1) - (l4-1));
                
                YCoeff0(l1,l2,l3,l4) =YCoeff(l1,l2,l3,l4).*mu11(l1).*mu22(l2).*sigma22(l3).*sigma11(l4);
                YqCoeff0(l1,l2,l3,l4) =YqCoeff(l1,l2,l3,l4).*mu11(l1).*mu22(l2).*sigma22(l3).*sigma11(l4);
                YqzCoeff0(l1,l2,l3,l4) =YqCoeff(l1,l2,l3,l4).*mu33(l1).*mu44(l2).*sigma22(l3).*sigma11(l4);
            end
        end
    end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


wnStart=1;%
yy(wnStart:Nn)=((1-gamma)*w(wnStart:Nn)).^(1/(1-gamma));
%The above yy(wnStart:Nn)=x0;

tic


for tt=1:Tt 
    t2=tt*dt;
    t1=(tt-1)*dt;
    if(tt==1)
       
        [wMu0dt,c1,c22] = CalculateDriftAndVolA8Trans(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt);
        w(1:Nn)=x0^(1-gamma)/(1-gamma)+wMu0dt(1)+c1(1).*Z(1:Nn);
        

    end
    if((tt>1) && (tt<=16))
        %The first sixteen steps are simulated using a simple and slightly
        %altered version of the method I have used for simple CEV noises
        %and brownian motions. I used it only for starting few time steps
        %since density remains pretty much very close to linear here. If
        %that is not the case, you would have to alter this.
       [wMu0dt,wMu1dt,dwMu0dtdw,d2wMu0dtdw2,c1] = CalculateDriftAndVolA404(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt);
        %dw(wnStart:Nn)=c1(wnStart:Nn);%.*Z(wnStart:Nn) ;% ...
       dw(wnStart:Nn)=c1(wnStart:Nn).*Z(wnStart:Nn) ;% ...
       dw2(wnStart:Nn)=dw(wnStart:Nn).^2;
       [wMid] = InterpolateOrderN8(8,0,Z(NnMidl-3),Z(NnMidl-2),Z(NnMidl-1),Z(NnMidl),Z(NnMidh),Z(NnMidh+1),Z(NnMidh+2),Z(NnMidh+3),w(NnMidl-3),w(NnMidl-2),w(NnMidl-1),w(NnMidl),w(NnMidh),w(NnMidh+1),w(NnMidh+2),w(NnMidh+3));
       B(1:Nn)=w(1:Nn)-wMid;
       [dBdZ,d2BdZ2,d3BdZ3] = First3Derivatives2ndOrderEqSpacedA(wnStart,Nn,dNn,B,Z);
       B(wnStart:Nn)=sign(B(wnStart:Nn)+dw(wnStart:Nn)).* ...
            sqrt(abs(sign(B(wnStart:Nn)).*(B(wnStart:Nn)).^2+ ...
            sign(dw(wnStart:Nn)).*dw2(wnStart:Nn)));
        
        w(wnStart:Nn)=wMid+wMu0dt(wnStart:Nn)+B(wnStart:Nn);
        
        
        
    end
    %Now starts the calculation for SDE simulation using probability mass
    %transfer.
    if(tt>16)
                
        [wMu0dt,wMu1dt,dwMu0dtdw,d2wMu0dtdw2,c1] = CalculateDriftAndVolA404(w,wnStart,Nn,YqCoeff0,Fp1,gamma,dt); 
      
        dw(wnStart:Nn)=c1(wnStart:Nn) ;% ...
        dw2(wnStart:Nn)=dw(wnStart:Nn).^2;
        %[wMid] = InterpolateOrderN6(6,0,Z(NnMidl-2),Z(NnMidl-1),Z(NnMidl),Z(NnMidh),Z(NnMidh+1),Z(NnMidh+2),w(NnMidl-2),w(NnMidl-1),w(NnMidl),w(NnMidh),w(NnMidh+1),w(NnMidh+2));
        [wMid] = InterpolateOrderN8(8,0,Z(NnMidl-3),Z(NnMidl-2),Z(NnMidl-1),Z(NnMidl),Z(NnMidh),Z(NnMidh+1),Z(NnMidh+2),Z(NnMidh+3),w(NnMidl-3),w(NnMidl-2),w(NnMidl-1),w(NnMidl),w(NnMidh),w(NnMidh+1),w(NnMidh+2),w(NnMidh+3));
        B(1:Nn)=w(1:Nn)-wMid;
        B1=B;
        [dBdZ_0,d2BdZ2_0,d3BdZ3_0] = First3Derivatives2ndOrderEqSpacedA(wnStart,Nn,dNn,B,Z);
        %Above are derivative names with an appended zero "_0". These are derivatives on the 
        %Nn grid (time t+1 grid). When there are no appended zeros, those are
        %derivatives on the Nn1 grid i.e time t grid.
       
     
        if(tt<=32)
            for nn=1:20
                xx0(nn)=Z(1)-nn*dNn;  %Z values corresponding to points to be extrapolated.
                xx1(nn)=Z(nn);        %Z Values corresponding to boundary points used to extrapolate.%We use only first ten out of 20.
                yy1(nn)=B1(nn);       %resultant values for points used to extrapolate.%We use only first ten out of 20.
            end
            %%[yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            %In the loop below, the interpolated values are assigned to
            %variable BB1 which extends form 1:Nn1. We would use this
            %variable BB1(Bm(t) in the notes) later as values at time t to simulate the values
            %of Bn at time t+1.
            for nn=1:20
                BB1(21-nn)=yy0(nn);
                %%BB1(21-nn)=Btemp-yy0(nn)*dNn;
                %%Btemp=BB1(21-nn);
            end
            %In the loop below main body of the variable is allocated to
            %the array BB1 in notes "Bm(t)"
            for nn=1:Nn
                BB1(nn+20)=B1(nn); 
            end
            
            %Below we do extrapolation on right boundary from 5SD to 6 SD
            %and then assign it to BB1 which is Bm(t).
            for nn=1:20
                xx0(nn)=Z(Nn)+nn*dNn;
                xx1(nn)=Z(Nn-nn+1);
                %%yy1(nn)=dBdZ_0(Nn-nn+1);
                yy1(nn)=B1(Nn-nn+1);
            end
            [yy0] = InterpolateOrderN10(10,xx0,xx1(1),xx1(2),xx1(3),xx1(4),xx1(5),xx1(6),xx1(7),xx1(8),xx1(9),xx1(10),yy1(1),yy1(2),yy1(3),yy1(4),yy1(5),yy1(6),yy1(7),yy1(8),yy1(9),yy1(10));
            
            for nn=1:20
                BB1(Nn+20+nn)=yy0(nn);
                
            end
            
            %The function below calculates grid cell boundaries from mid
            %points of the grids using interpolation and relevant Z. The
            %grid is equidistant and symmetric with respect to underlying Z
            %but not with respect to the Bessel variable. We use the value
            %of Z at boundaries of each cell to interpolate the value of
            %bessel variable there.
            [BB1a,BB1b] = CalculateGridStartsAndEndsBoundedEnds(BB1,Z1,1,Nn1,dNn);
            
            %Below,I later assigned Z1 to ZZ1 and N1 to NN1 ans similarly for
            %Z1Prob since earlier I had several(three different) cases of 
            %extrapolation ranging from 5 to 6 SD, and 5 to 5.5 SD and 5 to 5.25 SD.
            %I Was thinking when time would advance and grid would have
            %expanded and if dt would stay the same, the user might be
            %better off choosing a smaller grid with better extrapolation. 
            
            ZZ1=Z1;
            NN1=Nn1;
            ZZProb(1:NN1)=Z1Prob(1:Nn1);
        end
            %plot(ZZ1(1:NN1),BB1(1:NN1),'b',ZZ1(1:NN1),BB1a(1:NN1),'y',ZZ1(1:NN1),BB1b(1:NN1),'k',Z(1:Nn),B1(1:Nn),'r')
            %str=input('Look at B1 and BB1, original and extrapolated version and boundaries');
            
            %Below calculate first four derivatives. Please replace with your favorite
            %robust function. 
            [dBdZ,d2BdZ2,d3BdZ3] = First3Derivatives2ndOrderEqSpacedA(1,NN1,dNn,BB1,Z1);
            [dwdZAA,d2wdZ2AA,d3wdZ3AA,d4BdZ4] = First4Derivatives2ndOrderEqSpaced(1,NN1,dNn,BB1,Z1);
        
            %plot((1:NN1),dBdZ(1:NN1),'r')
            %str=input('Look at 1st derivative');
            %plot((1:NN1),d2BdZ2(1:NN1),'r')
            %str=input('Look at 2nd derivative');
            %plot((1:NN1),d3BdZ3(1:NN1),'r')
            %str=input('Look at 3rd derivative');
        
            %Below calculate hermite polynomials of Z1 underlying the 
            %Grid BB1 which is "Bm(t)" grid. We will use these hermite 
            %polynomials and later derivatives to calculate the derivatives of 
            %density of Bm with respect to Bm. dpdBm calcualted at centre
            %of the grid cells. 
       
            He1(1:NN1)=Z1(1:NN1);
            He2(1:NN1)=Z1(1:NN1).^2-1;
            He3(1:NN1)=Z1(1:NN1).^3-3*Z1(1:NN1);
            He4(1:NN1)=Z1(1:NN1).^4-6*Z1(1:NN1).^2+3;
            He5(1:NN1)=Z1(1:NN1).^5-10*Z1(1:NN1).^3+15;
            Zpdf(1:NN1)=normpdf(Z1(1:NN1),0,1);
            dZpdf(1:NN1)=-He1(1:NN1).*Zpdf(1:NN1);
            d2Zpdf(1:NN1)=He2(1:NN1).*Zpdf(1:NN1);
            d3Zpdf(1:NN1)=-He3(1:NN1).*Zpdf(1:NN1);
            d4Zpdf(1:NN1)=He4(1:NN1).*Zpdf(1:NN1);
            d5Zpdf(1:NN1)=-He5(1:NN1).*Zpdf(1:NN1);

            %Please note that in calculations below, we are using derivatives without 
            %appended zeros since they are on BB1 "Bm(t)" grid that ranges from 1:Nn1 or equivalently 1:NN1. 
            dZdB(1:NN1)=1.0./dBdZ(1:NN1);
            d2ZdB2(1:NN1)=-d2BdZ2(1:NN1).*dZdB(1:NN1).^3;
            d3ZdB3(1:NN1)=-d3BdZ3(1:NN1).*dZdB(1:NN1).^4+3*d2BdZ2(1:NN1).^2.*dZdB(1:NN1).^5;
            d4ZdB4(1:NN1)=-d4BdZ4(1:NN1).*dZdB(1:NN1).^5-4*d3BdZ3(1:NN1).*d2ZdB2(1:NN1).*dZdB(1:NN1).^3+ ...
            6*d2BdZ2(1:NN1).*d3BdZ3(1:NN1).*dZdB(1:NN1).^6+15*d2BdZ2(1:NN1).^2.*d2ZdB2(1:NN1).*dZdB(1:NN1).^6 ;
            d5ZdB5(1:NN1)=0.0;
            d6ZdB6(1:NN1)=0.0;
       
       
            
            pm0(1:NN1)=Zpdf(1:NN1).*dZdB(1:NN1);
            dpm0(1:NN1)=dZpdf(1:NN1).*dZdB(1:NN1).^2+Zpdf(1:NN1).*d2ZdB2(1:NN1);
            d2pm0(1:NN1)=d2Zpdf(1:NN1).*dZdB(1:NN1).^3+3*dZpdf(1:NN1).*dZdB(1:NN1).*d2ZdB2(1:NN1)+Zpdf(1:NN1).*d3ZdB3(1:NN1);
            d3pm0(1:NN1)=d3Zpdf(1:NN1).*dZdB(1:NN1).^4+6*d2Zpdf(1:NN1).*dZdB(1:NN1).^2.*d2ZdB2(1:NN1) + ...
                4*dZpdf(1:NN1).*dZdB(1:NN1).*d3ZdB3(1:NN1) + 3*dZpdf(1:NN1).*d2ZdB2(1:NN1).^2+ Zpdf(1:NN1).*d4ZdB4(1:NN1);
    
            d4pm0(1:NN1)=d4Zpdf(1:NN1).*dZdB(1:NN1).^5+10*d3Zpdf(1:NN1).*dZdB(1:NN1).^3.*d2ZdB2(1:NN1) + ...
                15*d2Zpdf(1:NN1).*dZdB(1:NN1).*d2ZdB2(1:NN1).^2 + ...
                10*d2Zpdf(1:NN1).*dZdB(1:NN1).^2.*d3ZdB3(1:NN1) + ...
                10*dZpdf(1:NN1).*d2ZdB2(1:NN1).*d3ZdB3(1:NN1) + ...
                5*dZpdf(1:NN1).*dZdB(1:NN1).*d4ZdB4(1:NN1)+ Zpdf(1:NN1).*d5ZdB5(1:NN1);
        
            d5pm0(1:NN1)=d5Zpdf(1:NN1).*dZdB(1:NN1).^6+15*d4Zpdf(1:NN1).*dZdB(1:NN1).^4.*d2ZdB2(1:NN1) + ...
                45*d3Zpdf(1:NN1).*dZdB(1:NN1).^2.*d2ZdB2(1:NN1).^2 + ...
                20*d3Zpdf(1:NN1).*dZdB(1:NN1).^3.*d3ZdB3(1:NN1) + ...
                15*d2Zpdf(1:NN1).*d2ZdB2(1:NN1).^3 + ...
                60*d2Zpdf(1:NN1).*dZdB(1:NN1).*d2ZdB2(1:NN1).*d3ZdB3(1:NN1) + ...
                15*d2Zpdf(1:NN1).*d2ZdB2(1:NN1).^2.*d4ZdB4(1:NN1)+ ...
                10*dZpdf(1:NN1).*d3ZdB3(1:NN1).^2+ ...
                15*dZpdf(1:NN1).*d2ZdB2(1:NN1).*d4ZdB4(1:NN1)+ ...
                6*dZpdf(1:NN1).*dZdB(1:NN1).*d5ZdB5(1:NN1)+ ...
                Zpdf(1:NN1).*d6ZdB6(1:NN1);
   
    
            %str=input('Look at derivatives of initial probability');
            %Below I reconstruct the new variable ww1(1:Nn1)=w(1:NN1) which is an
            %extrapolated version of w(1:Nn). I have used a first order
            %improved version that is still locally gaussian but has
            %slightly different variance across the grid. I might change it
            %in new later versions and use a gaussian grid with dt variance on
            %which even non-bessel coordinate variables in original coordinates would
            %be possibly simulated. ww1 is reconstructed by adding the mean
            %we had subtracted.
            
            ww1(1:NN1)=BB1(1:NN1)+wMid;
            %cc1 below is volatility associated with each grid cell at time
            %t Bm(t) or BB1.
            [wwMu0dt,wwMu1dt,wdwMu0dtdw,wd2wMu0dtdw2,cc1] = CalculateDriftAndVolA404(ww1,1,NN1,YqCoeff0,Fp1,gamma,dt); 
            %plot(ZZ1(1:NN1),ww1(1:NN1),'b',Z(1:Nn),w(1:Nn),'r')
            %str=input('Look at comparison of interpolated and original w-0');
            %plot(ZZ1(1:NN1),cc1(1:NN1),'b',Z(1:Nn),c1(1:Nn),'r')
            %str=input('Look at comparison of original and interpolated vol coefficient-1');
            %plot(ZZ1(1:NN1),cc1(1:NN1),'b',Z(1:Nn),c1(1:Nn),'r')
            %str=input('Look at comparison of original and interpolated vol coefficient-1A');
            %plot(ZZ1(1:NN1),wwMu0dt(1:NN1),'b',Z(1:Nn),wMu0dt(1:Nn),'r')
            %str=input('Look at drifts origianl and interpolated-2');
            %plot(ZZ1(1:NN1),ZZProb(1:NN1),'b',Z(1:Nn),ZProb(1:Nn),'r')
            %str=input('Look at Zprobss -3');
            %plot((1:Nn),Z(1:Nn),'r',(1:NN1)-20,ZZ1(1:NN1),'b')
            %str=input('Look at Zs -4');
       
            %Below are calculations of CDF and its derivatives to calculate
            %the mid point of the grid at time t+1. This mid point should
            %lie exactly on median which means CDF there would be exactly
            %equal to .5 or CDF=.5.
            PoutMid=0;
            poutMid=0;
            dpoutdBMid=0.0;
            d2poutdB2Mid=0.0;
            d3poutdB3Mid=0.0;
       
            for mm=1:NN1
                %0.0 as argument is the trial guess where CDF and
                %derivatives are calculated.
                [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(0.0,cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
                %Sometimes due to my bad extrapolation at boundaries, some
                %values at extreme boundary were NAN so I added this fix.
                if(isnan(Pmn)==1)
                    Pmn=0;
                    pmn=0;
                    dpmn=0;
                    d2pmn=0;
                    d3pmn=0;
                end
            
                %Below is summation of CDF from each cell at mid trial point. 
                %And so on for derivatives of CDF. dCDFdBn. d2CDFdBn2.and so
                %on.
                PoutMid=PoutMid+ Pmn;
                poutMid=poutMid+pmn;
                dpoutdBMid=dpoutdBMid+dpmn;
                d2poutdB2Mid=d2poutdB2Mid+d2pmn;
                d3poutdB3Mid=d3poutdB3Mid+d3pmn;
                   
            end
            ExcessCDF=PoutMid-.5;
            %Below +1 flag is used when we are finding CDF towards right side.
            %At Right boundary.
            [dB] =SolveQuarticRootForProb(ExcessCDF,poutMid,dpoutdBMid,d2poutdB2Mid,d3poutdB3Mid,+1);
            dB=real(dB);
            dB
            BnMid=dB; %The true value of median for Bn(t+1)
            str=input('Look at dB at median');
      
            %Now We calculate the right boundary of each cell from 0 SD to +5SD
            %B2a with an appended "a" is the left boundary.
            %B2b with an appended "b" is the right boundary.
            B2a(NnMidh)=BnMid;%  
            %I used this to calculate the cumulative defect in CDF towards the
            %right side.
            TotalExcessCDF2=0;
       
            for nn=NnMidh:Nn  %Loop to the right from 0 SD to +5 SD over Bn(t+1).
            % Below is the good guess for dBndZ of the cell. This requires
            % multiplication with dNn.  dNn means dZ here.
            %Please note that we are using derivative with an appended zero
            %since this calculation is on grid 1:Nn: Bn(t+1,1:Nn)
            SigmaB(nn)=sqrt(dBdZ_0(nn).^2+ dw2(nn));
           
            %B3 is only an auxiliary variable.
            if(nn==NnMidh)
                B3(nn)=BnMid+ SigmaB(nn).*dNn/2;
            else
                B3(nn)=B3(nn-1)+SigmaB(nn).*dNn;
            end
            
            
            %B2(nn)=B2a(nn)+SigmaB(nn).*dNn/2;
            %Below is the guesses trial right boundary that we will try to
            %improve.
            B2b(nn)=B2a(nn)+SigmaB(nn).*dNn;

            PIn(nn)=0;
            Pout(nn)=0;
            pout(nn)=0;
            dpoutdB(nn)=0.0;
            d2poutdB2(nn)=0.0;
            d3poutdB3(nn)=0.0;
            for mm=1:NN1
               %I wrote this function to calculate CDF at left boundary
               %where derivatives are not needed.
               [Pmn] = CalculateCDFFromSubDiv(B2a(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
               
               if(isnan(Pmn)==1)
                Pmn=0;
               end
               PIn(nn)=PIn(nn)+ Pmn; %This is CDF at left boundary
               %Below the function calculates CDF and its derivatives
               %at right boundary where all derivatives are needed.
               [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
                   
               if(isnan(Pmn)==1)
                    Pmn=0;
                    pmn=0;
                    dpmn=0;
                    d2pmn=0;
                    d3pmn=0;
                end
                Pout(nn)=Pout(nn)+ Pmn;
                pout(nn)=pout(nn)+pmn;
                dpoutdB(nn)=dpoutdB(nn)+dpmn;
                d2poutdB2(nn)=d2poutdB2(nn)+d2pmn;
                d3poutdB3(nn)=d3poutdB3(nn)+d3pmn;
                   
            end
            ExcessCDF=(Pout(nn)-PIn(nn))-ZProb(nn);
       
            [dB] =SolveQuarticRootForProb(ExcessCDF,pout(nn),dpoutdB(nn),d2poutdB2(nn),d3poutdB3(nn),+1);
            %dB is how much to move the trial boundary so that probability
            %defect goes to zero
            dB=real(dB);

            B2b(nn)=B2b(nn)+dB;

            if(nn<Nn)
                B2a(nn+1)=B2b(nn);
            end
            %Below I made calculations to recalculate the CDF on improved
            %boundary to see how much the defect is after making adjustment
            %to trial boundary. This is not necessary.
            Pout2(nn)=0.0;
            for mm=1:NN1
               [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
                   if(isnan(Pmn)==1)
                       Pmn=0;
                       pmn=0;
                       dpmn=0;
                       d2pmn=0;
                       d3pmn=0;
                   end
                   Pout2(nn)=Pout2(nn)+ Pmn; 
            end
            %ExcessCDF2 below is the probability mass defect after boundary
            %improvment.
            ExcessCDF2=(Pout2(nn)-PIn(nn))-ZProb(nn);
            %TotalExcessCDF2 measures cumulative error in cdf and loops
            %over all cells to the right of median.
            TotalExcessCDF2=TotalExcessCDF2+ExcessCDF2;

%            ZProb(nn)
%            ExcessCDF
%            ExcessCDF2
%            TotalExcessCDF2
%            dB
%            nn
 %       str=input('Look nos-end');    
            
            
       end
       
       %Now we repeat the trial boundary improvement procedure to the left
       %of median 
       
       %B2b(nn) is right boundary here.
       B2b(NnMidl)=BnMid;
       for nn=NnMidl:-1:1
           % Below is the good guess for dBndZ of the cell. This requires
           % multiplication with dNn. dNn means dZ here.
           %Please note that we are using derivative with an appended zero
           %since this calculation is on grid 1:Nn: Bn(t+1,1:Nn)
             
            SigmaB(nn)=sqrt(dBdZ_0(nn).^2+ dw2(nn));
            if(nn==NnMidl)
                B3(nn)=BnMid-SigmaB(nn).*dNn/2;
            else
                B3(nn)=B3(nn+1)-SigmaB(nn).*dNn;
            end
            %B2(nn)=B2b(nn)-SigmaB(nn).*dNn/2;
            %Trial left boundary below
            B2a(nn)=B2b(nn)-SigmaB(nn).*dNn;
            PIn(nn)=0;
            Pout(nn)=0.0;
            pin(nn)=0;
            dpindB(nn)=0.0;
            d2pindB2(nn)=0.0;
            d3pindB3(nn)=0.0;
            for mm=1:NN1
                  [Pmn] = CalculateCDFFromSubDiv(B2b(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));

                  if(isnan(Pmn)==1)
                       Pmn=0;
                   end
                    
                    Pout(nn)=Pout(nn)+ Pmn;

                    [Pmn,pmn,dpmn,d2pmn,d3pmn] = CalculateCDFAndDerivativesFromSubDivSign(B2a(nn),cc1(mm),BB1(mm),BB1a(mm),BB1b(mm),ZZProb(mm),pm0(mm),dpm0(mm),d2pm0(mm),d3pm0(mm),d4pm0(mm),d5pm0(mm));
 
                   if(isnan(Pmn)==1)
                       Pmn=0;
                       pmn=0;
                       dpmn=0;
                       d2pmn=0;
                       d3pmn=0;
                   end 
                   PIn(nn)=PIn(nn)+ Pmn;
                   
                   pin(nn)=pin(nn)+pmn;
                   dpindB(nn)=dpindB(nn)+dpmn;
                   d2pindB2(nn)=d2pindB2(nn)+d2pmn;
                   d3pindB3(nn)=d3pindB3(nn)+d3pmn;
            end
            ExcessCDF=(Pout(nn)-PIn(nn))-ZProb(nn);
            %nn
            %ZProb(nn)
            %ExcessCDF
            %pout(nn)
            %dpoutdB(nn)
            %negative one "-1" flag for negative side.
            [dB] =SolveQuarticRootForProb(ExcessCDF,pin(nn),dpindB(nn),d2pindB2(nn),d3pindB3(nn),-1);
            dB=real(dB);
            %str=input('Look at numbers in second part')
            B2a(nn)=B2a(nn)+dB;
            if(nn>1)
            B2b(nn-1)=B2a(nn);
            end
       end

%       
%       plot((1:Nn),SigmaB(1:Nn),'b');
%       str=input('Look at SigmaB');
       
       
%Below we calculate the mid points of grid cells from grid boundaries.       
       [B2] = CalculateGridSubs(B2a,B2b,Z,wnStart,Nn,dNn);
       
%Below B1 is old Bm(t). B2 is Bn(t+1). B3 is guessed Bn(t+1)(improved version since it is built on true deviations)
       plot((1:Nn),B1(1:Nn),'r',(1:Nn),B2(1:Nn),'b',(1:Nn),B3(1:Nn),'k')
       str=input('Look at comparison of new and old Bs');
       
%Below we reconstruct wn from Bn by adding wmid and the drift.        
       w(wnStart:Nn)=wMid+wMu0dt(wnStart:Nn)+B2(wnStart:Nn);
%Below is the grsph of newly calculated value of w.       
       plot((1:Nn),w(1:Nn),'r')
       str=input('Calculated Value of w');
    end
end
    


%below D's (the names of variables starting with D) are 
%change of probability derivatives.

y_w(1:Nn)=0;
y_w(wnStart:Nn) = ((1-gamma)*w(wnStart:Nn)).^(1/(1-gamma));
Dfy_w(wnStart:Nn)=0;
for nn=wnStart+1:Nn-1
    Dfy_w(nn) = (y_w(nn + 1) - y_w(nn - 1))/(Z(nn + 1) - Z(nn - 1));
    %Change of variable derivative for densities
end
py_w(1:Nn)=0;
for nn = wnStart:Nn-1
    py_w(nn) = (normpdf(Z(nn),0, 1))/abs(Dfy_w(nn));%Origianl coordinates density
end

toc

ItoHermiteMean=sum(y_w(wnStart+1:Nn-1).*ZProb(wnStart+1:Nn-1)) %Original process average from coordinates 
disp('true Mean only applicable to standard SV mean reverting type models otherwise disregard');
TrueMean=theta+(x0-theta)*exp(-kappa*dt*Tt)%Mean reverting SDE original variable true average

rng(29079137, 'twister')
paths=200000;
YY(1:paths)=x0;  %Original process monte carlo.
Random1(1:paths)=0;
for tt=1:TtM
    
    Random1=randn(size(Random1));
    HermiteP1(1,1:paths)=1;
    HermiteP1(2,1:paths)=Random1(1:paths);
    HermiteP1(3,1:paths)=Random1(1:paths).^2-1;
    HermiteP1(4,1:paths)=Random1(1:paths).^3-3*Random1(1:paths);
    HermiteP1(5,1:paths)=Random1(1:paths).^4-6*Random1(1:paths).^2+3;
    

    YY(1:paths)=YY(1:paths) + ...
        (YCoeff0(1,1,2,1).*YY(1:paths).^Fp(1,1,2,1)+ ...
        YCoeff0(1,2,1,1).*YY(1:paths).^Fp(1,2,1,1)+ ...
        YCoeff0(2,1,1,1).*YY(1:paths).^Fp(2,1,1,1))*dtM + ...
        (YCoeff0(1,1,3,1).*YY(1:paths).^Fp(1,1,3,1)+ ...
        YCoeff0(1,2,2,1).*YY(1:paths).^Fp(1,2,2,1)+ ...
        YCoeff0(2,1,2,1).*YY(1:paths).^Fp(2,1,2,1)+ ...
        YCoeff0(1,3,1,1).*YY(1:paths).^Fp(1,3,1,1)+ ...
        YCoeff0(2,2,1,1).*YY(1:paths).^Fp(2,2,1,1)+ ...
        YCoeff0(3,1,1,1).*YY(1:paths).^Fp(3,1,1,1))*dtM^2 + ...
        ((YCoeff0(1,1,1,2).*YY(1:paths).^Fp(1,1,1,2).*sqrt(dtM))+ ...
        (YCoeff0(1,1,2,2).*YY(1:paths).^Fp(1,1,2,2)+ ...
        YCoeff0(1,2,1,2).*YY(1:paths).^Fp(1,2,1,2)+ ...
        YCoeff0(2,1,1,2).*YY(1:paths).^Fp(2,1,1,2)).*dtM^1.5) .*HermiteP1(2,1:paths) + ...
        ((YCoeff0(1,1,1,3).*YY(1:paths).^Fp(1,1,1,3) *dtM) + ...
        (YCoeff0(1,1,2,3).*YY(1:paths).^Fp(1,1,2,3)+ ...
        YCoeff0(1,2,1,3).*YY(1:paths).^Fp(1,2,1,3)+ ...
        YCoeff0(2,1,1,3).*YY(1:paths).^Fp(2,1,1,3)).*dtM^2).*HermiteP1(3,1:paths) + ...
        ((YCoeff0(1,1,1,4).*YY(1:paths).^Fp(1,1,1,4)*dtM^1.5 )).*HermiteP1(4,1:paths) + ...
        (YCoeff0(1,1,1,5).*YY(1:paths).^Fp(1,1,1,5)*dtM^2.0).*HermiteP1(5,1:paths);
    

end

YY(YY<0)=0;
disp('Original process average from monte carlo');
MCMean=sum(YY(:))/paths %origianl coordinates monte carlo average.
MCVar=sum((YY(:)-MCMean).^2)/paths
disp('Original process average from our simulation');
ItoHermiteMean=sum(y_w(wnStart+1:Nn-1).*ZProb(wnStart+1:Nn-1)) %Original process average from coordinates 
ItoHermiteVar=sum((y_w(wnStart+1:Nn-1)-ItoHermiteMean).^2.*ZProb(wnStart+1:Nn-1)) 
disp('true Mean only applicble to standard SV mean reverting type models otherwise disregard');
TrueMean=theta+(x0-theta)*exp(-kappa*dt*Tt)%Mean reverting SDE original variable true average

MaxCutOff=30;
NoOfBins=round(300*gamma^2*4*sigma0/sqrt(MCMean)/(1+kappa));%Decrease the number of bins if the graph is too 
[YDensity,IndexOutY,IndexMaxY] = MakeDensityFromSimulation_Infiniti_NEW(YY,paths,NoOfBins,MaxCutOff );

%plot(y_w1(wnStart+1:Nn-1),py_w1(wnStart+1:Nn-1),'b',y_w(wnStart+1:Nn-1),py_w(wnStart+1:Nn-1),'r',IndexOutY(1:IndexMaxY),YDensity(1:IndexMaxY),'g');
%plot(y_w(wnStart+1:Nn-1),py_w(wnStart+1:Nn-1),'r',IndexOutY(1:IndexMaxY),YDensity(1:IndexMaxY),'g');
plot(y_w(wnStart+1:Nn-1),py_w(wnStart+1:Nn-1),'r',IndexOutY(1:IndexMaxY),YDensity(1:IndexMaxY),'g');

title(sprintf('x0 = %.4f,theta=%.3f,kappa=%.2f,gamma=%.3f,sigma=%.2f,T=%.2f,dt=%.5f,M=%.4f,TM=%.4f', x0,theta,kappa,gamma,sigma0,T,dt,ItoHermiteMean,TrueMean));%,sprintf('theta= %f', theta), sprintf('kappa = %f', kappa),sprintf('sigma = %f', sigma0),sprintf('T = %f', T));
 
legend({'New Model Density','Monte Carlo Density'},'Location','northeast')
 
str=input('red line is density of SDE from Ito-Hermite method, green is monte carlo.');
end
Here is the graph output.




Image