⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pathbranchdemo.java

📁 金融资产定价,随机过程,MONTE CARLO 模拟 JAVA 程序和文档资料
💻 JAVA
字号:
/* WARANTY NOTICE AND COPYRIGHTThis program is free software; you can redistribute it and/ormodify it under the terms of the GNU General Public Licenseas published by the Free Software Foundation; either version 2of the License, or (at your option) any later version.This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See theGNU General Public License for more details.You should have received a copy of the GNU General Public Licensealong with this program; if not, write to the Free SoftwareFoundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.Copyright (C) Michael J. Meyermatmjm@mindspring.comspyqqqdia@yahoo.com*//* * PathBranchDemo.java * * Created on March 29, 2002, 9:10 PM */package Examples.Probability;import Processes.*;import java.lang.Math.*;import java.awt.*;import javax.swing.JFrame;import java.awt.event.*;import javax.swing.WindowConstants;/** <p>Main method provides animated graphics to illustrate the concept of *  conditioning through path branching. Let W=W(t), 0&lt=t&lt=T, be a standard *  one dimensional Brownian motion starting at zero. The variable W(T) will *  be conditioned on the value of W(T/2).<p> * *  <p>The unconditional distribution of W(T) is normal with mean zero and  *  variance T. The conditional distribution has mean *  W(T/2) and variance T/2.<p> * *  <p>A single path is generated up to time t=T/2 (the information). *  Paths branching from this one at time t will be displayed *  as they generate the histogram of the conditional distribution of W(T) *  conditioned on the value of W(T/2).</p> * *  <p>The range of data (values of W(T)) sampled by the histogram is chosen to *  be the interval [-1.75T,1.75T], that is 1.75 variances around the *  unconditional mean.</p> * * @author  Michael J. Meyer */public class PathBranchDemo extends JFrame{        int  // dimensions of JFrame window        window_width,        window_height,        // upper right corner of display rectangle        x_offset,            y_offset,        // dimensions of display rectangle        width,        height,        // Brownian motion        T,                        // time steps to horizon, must divide width        nBins,                    // number of bins, must divide height        nPaths;                   // number of paths used to fill the histogram        double dt;                    //size of time step        int[] bins;                    // array of histogram bins        // range [min,max] of histogram    double min, max, binWidth;                 BrownianMotion W;          // must start at midpoint of left edge                               // of display rectangle        /** DISPLAY RECTANGLE:     *  The graphs of the Brownian motion paths are displayed within the      *  display rectangle in the JFrame window. Location in user coordinates:      *  upper right corner = (x_offset,y_offset).      *     *  The Brownian motion starts at the midpoint of the left edge     *  of the display rectangle, that is, at the point     *  (x_offset, y_offset+height/2) in the user coordinates of (this)     *  window.      */    /*******************************************************************************                     COORDINATE TRANSFORMATION *******************************************************************************/         /** Note that we have 3 coordinate systems:      *      *  1. The user coordine system of (this) window.       *  The coordinates are pixels, origin is at the left upper corner of the       *  window, x,y-axes are oriented right,down.      *      *  2. (Our) standard pixel coordinate system.      *  Coordinates are pixels, origin is at the midpoint of the left edge       *  of the display rectangle (where the Brownian motion starts),      *  x,y-axes are oriented right,up.      *      *  3. The real coordinate system. Real Euclidean coordinates.      *  Origin same as standard pixel coordinates, x,y-axes oriented      *  right,up.      *      *  Only user coordinates can be handed to the java.awt.Graphics      *  drawing routines. Therefore we need the following conversion routines:      * /                /** Converts standard pixel x coordinate a to user x coordinate.      */      int x(int a){ return a+x_offset; }                  /** Converts standard pixel y coordinate b to user y coordinate.      */      int y(int b){ return y_offset+height/2-b; }                      /** Converts real x coordinate a to user x coordinate.      *  To do this we first convert to standard pixel x-ccordinate.      *  Note: T*dt=width stabdard pixles, so      *  a=(a/(T*dt))*width standard pixles.      */      int xx(double a)      {            // a in standard pixles          int aa=(int)Math.round((a/(T*dt))*width);          return x(aa);      }                  /** Converts real y coordinate b to user y coordinate.      *  To do this we first convert to standard pixel y-ccordinate.      *  Note: max-min=height standard pixles, so      *  b=(b/(max-min))height standard pixels      */      int yy(double b)      {           // b in standard pixles          int bb=(int)Math.round((b/(max-min))*height);          return y(bb);      }      /*******************************************************************************                     DRAWING ROUTINES                    *******************************************************************************/                 /** Draw the graph t -> (t,W(t)) of the current path of the Brownian      *  motion W between times t=t_0 and t=t_1.      */      private void drawPathGraph(int t_0, int t_1, Graphics g)      {           double[] z=W.get_path();                      // unit f of length: width=(T*dt)*f so            double f=width/(T*dt);                       // time step in pixels           int dpix=width/T;                      // graph of path starts           int u=x(t_0*dpix),v=yy(z[t_0]);                      for(int t=t_0;t<t_1;t++)           {               // next point on graph of path               int u1=x((t+1)*dpix), v1=yy(z[t+1]);               // connect the points               g.drawLine(u,v,u1,v1);                // move to next point              u=u1; v=v1;           }      } // end drawPathGraph      /*******************************************************************************              HISTOGRAM FILLING, NORMALIZING, DRAWING *******************************************************************************/                      /** Fills the current value W(T) into its histogram bin       *  and update the column in the histogram display       */      private void bin(Graphics g)      {          double[] z=W.get_path();          int j=(int)((z[T]-min)/binWidth);   // bin index                    if((0<=j)&&(j<nBins))          {              bins[j]++;                        // histogram column width in pixels             int cw=height/nBins;             // normalize os area under the histogram is 100 by 100 square pixels.             // if each entry pushes up a column by one pixel area will be             // nPaths*cw square pixels             double f=nPaths*cw/10000;                       // update the edge of column j, standard pixel coordinates;             // use f to normalize the histogram area.             g.setColor(Color.red);             int a=width+(int)(bins[j]/f), b1=-height/2+j*cw, b2=b1+cw;             g.drawLine(x(a),y(b1),x(a),y(b2));             g.setColor(Color.black);          } // end if                } // end bin                    /*******************************************************************************                     CONSTRUCTOR *******************************************************************************/                        /** Constructor     */    public PathBranchDemo    (int width, int height, int x_offset, int y_offset,     int T, int nBins, int nPaths, double dt)    {        this.width=width;        this.height=height;        this.x_offset=x_offset;        this.y_offset=y_offset;        this.T=T;        this.nBins=nBins;        this.nPaths=nPaths;        this.dt=dt;                window_width=width+x_offset+300;        window_height=height+2*y_offset;                // allocate bin array        bins=new int[nBins];                // set min, max;          // 1.75 unconditional standard deviations around the mean        min=-1.75*T*dt;        max=-min;        binWidth=(max-min)/nBins;                // Brownian motion starting at zero        W=new BrownianMotion(T,dt,0);                       setEnabled(true);        setTitle("Click to restart, close to kill");        setDefaultCloseOperation(EXIT_ON_CLOSE);        setSize(window_width,window_height);        setVisible(false);                // repaint on mouseclick        addMouseListener(new MouseAdapter(){	                                 	   public void mouseClicked(java.awt.event.MouseEvent event) 	   {  paint(getGraphics());  }                    }); // end mouseListener            } // end constructor                        /*******************************************************************************                         PAINT SELF *******************************************************************************/                public void paint(final Graphics g)    {           // clear histogram           for(int i=0;i<nBins;i++)bins[i]=0;           // clear the window           g.setColor(Color.white);           g.fillRect(0,0,window_width,window_height); // clear drawing           g.setColor(Color.black);                      // the display rectangle           g.drawRect(x_offset,y_offset,width,height);                      // label the time axis, text           g.drawString("Conditioning W(T) on W(T/2):",                        x(0),y(height/2+20));           g.drawString("Paths of W:",x(40),y(height/2-40));           g.drawString("Conditional histogram (red):",                        x(width+20),y(height/2-20));           g.drawString("(30,000 paths):",                        x(width+20),y(height/2-40));           g.drawString("t=0",x(-10),y(-height/2-12));           g.drawString("T/2",x(width/2-7),y(-height/2-12));           g.drawString("T",x(width-2),y(-height/2-12));                      // bisect display rectangle vertically           g.drawLine(x(width/2),y(-height/2),x(width/2),y(height/2));                              // draw the path graph to the time t=T/2 of conditioning           W.newPath();           drawPathGraph(0,T/2,g);                                /** Draw the branches and fill the histogram.            */           for(int i=0;i<nPaths;i++)           {               // draw a new path graph               W.newPathBranch(T/2);               // bin the terminal value               bin(g);               // draw the graph of the path branch               drawPathGraph(T/2,T,g);                          }        }// end paint                    /*******************************************************************************                         SHOW YOURSELF *******************************************************************************/                  public static void main(String[] args)      {            int  // upper right corner of display rectangle                x_offset=100,                    y_offset=100,                // dimensions of display rectangle                width=500,                height=400,                // Brownian motion                T=100,                  // time steps to horizon                nBins=200,              // number of bins in the histogram                                        // must divide height                nPaths=30000;           // number of paths               double dt=0.05;              //size of time step                     new PathBranchDemo               (width,height,x_offset,y_offset,T,nBins,nPaths,dt).show();       } // end main    } // end PathBranchDemo

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -