KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > nfunk > jep > function > Dot


1 /*****************************************************************************
2
3 JEP - Java Math Expression Parser 2.3.0
4       October 3 2004
5       (c) Copyright 2004, Nathan Funk and Richard Morris
6       See LICENSE.txt for license information.
7
8 *****************************************************************************/

9
10 package org.nfunk.jep.function;
11
12 import java.util.*;
13 import org.nfunk.jep.*;
14
15 public class Dot extends PostfixMathCommand
16 {
17     static Add add = new Add();
18     static Multiply mul = new Multiply();
19     public Dot()
20     {
21         numberOfParameters = 2;
22     }
23     
24     public void run(Stack inStack)
25         throws ParseException
26     {
27         checkStack(inStack); // check the stack
28

29         Object JavaDoc param2 = inStack.pop();
30         Object JavaDoc param1 = inStack.pop();
31         
32         inStack.push(dot(param1, param2));
33
34         return;
35     }
36     
37     public Object JavaDoc dot(Object JavaDoc param1, Object JavaDoc param2)
38         throws ParseException
39     {
40         if (param1 instanceof Vector && param2 instanceof Vector)
41         {
42             return dot((Vector) param1,(Vector) param2);
43         }
44         throw new ParseException("Dot: Invalid parameter type, both arguments must be vectors");
45     }
46     
47
48     public Object JavaDoc dot(Vector v1,Vector v2) throws ParseException
49     {
50         if(v1.size()!=v2.size())
51             throw new ParseException("Dot: both sides of dot must be same length");
52         int len = v1.size();
53         if(len<1)
54             throw new ParseException("Dot: empty vectors parsed");
55         
56         Object JavaDoc res = mul.mul(v1.elementAt(0),v2.elementAt(0));
57         for(int i=1;i<len;++i)
58         {
59             res = add.add(res,
60                 mul.mul(v1.elementAt(i),v2.elementAt(i)));
61         }
62         return res;
63     }
64 }
65
Popular Tags