KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lsmp > djep > xjep > function > Simpson


1 /* @author rich
2  * Created on 18-Nov-2003
3  *
4  * This code is covered by a Creative Commons
5  * Attribution, Non Commercial, Share Alike license
6  * <a HREF="http://creativecommons.org/licenses/by-nc-sa/1.0">License</a>
7  */

8 package org.lsmp.djep.xjep.function;
9
10 import java.util.*;
11
12 import org.nfunk.jep.*;
13 import org.nfunk.jep.function.*;
14
15 /**
16  * A sum function Sum(x^2,x,1,10) finds the sum of x^2 with x running from 1 to 10.
17  * Sum(x^2,x,1,10,2) calculates the 1^2+3^2+5^2+7^2+9^2 i.e. in steps of 2.
18  * @author Rich Morris
19  * Created on 10-Sept-2004
20  */

21 public class Simpson extends SumType {
22
23     static Add add = new Add();
24     static Multiply mul = new Multiply();
25
26     public Simpson()
27     {
28         super("Simpson");
29     }
30
31         
32     public Object JavaDoc evaluate(Object JavaDoc elements[]) throws ParseException
33     {
34         Object JavaDoc ret;
35         if(elements.length % 2 != 1)
36             throw new ParseException("Simpson: there should be an odd number of ordinates, its"+elements.length);
37
38         ret = add.add(elements[0],elements[elements.length-1]);
39         for(int i=1;i<elements.length-2;i+=2)
40         {
41             ret = add.add(ret,elements[i]);
42         }
43         return ret;
44     }
45     /* (non-Javadoc)
46      * @see org.lsmp.djep.xjep.function.SumType#evaluate(org.nfunk.jep.Node, org.nfunk.jep.Variable, double, double, double, java.lang.Object, org.nfunk.jep.ParserVisitor, java.util.Stack)
47      */

48     public Object JavaDoc evaluate(
49         Node node,
50         Variable var,
51         double min,
52         double max,
53         double inc,
54         Object JavaDoc data,
55         ParserVisitor pv,
56         Stack stack)
57         throws ParseException {
58         // TODO Auto-generated method stub
59
int i=0;
60         double val;
61         Object JavaDoc[] res=new Object JavaDoc[(int) ((max-min)/inc)+1];
62         for(i=0,val=min;val<=max;++i,val=min+i*inc)
63         {
64             var.setValue(new Double JavaDoc(val));
65                 
66             node.jjtGetChild(0).jjtAccept(pv,data);
67             checkStack(stack); // check the stack
68
res[i] = stack.pop();
69         }
70         Object JavaDoc ret = evaluate(res);
71         stack.push(ret);
72         return ret;
73     }
74
75 }
76
Popular Tags