KickJava   Java API By Example, From Geeks To Geeks.

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


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 Cross extends PostfixMathCommand
16 {
17     static Subtract sub = new Subtract();
18     static Multiply mul = new Multiply();
19     public Cross()
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(cross(param1, param2));
33
34         return;
35     }
36     
37     public Object JavaDoc cross(Object JavaDoc param1, Object JavaDoc param2)
38         throws ParseException
39     {
40         if (param1 instanceof Vector && param2 instanceof Vector)
41         {
42             return cross((Vector) param1,(Vector) param2);
43         }
44         throw new ParseException("Cross: Invalid parameter type, both arguments must be vectors");
45     }
46
47     public Object JavaDoc cross(Vector lhs,Vector rhs) throws ParseException
48     {
49         int len = lhs.size();
50         if((len!=2 && len!=3) || len !=rhs.size())
51             throw new ParseException("Cross: both sides must be of length 3");
52         if(len==3)
53         {
54             Vector res = new Vector(3);
55             res.setSize(3);
56             res.setElementAt(sub.sub(
57                     mul.mul(lhs.elementAt(1),rhs.elementAt(2)),
58                     mul.mul(lhs.elementAt(2),rhs.elementAt(1))),0);
59             res.setElementAt(sub.sub(
60                     mul.mul(lhs.elementAt(2),rhs.elementAt(0)),
61                     mul.mul(lhs.elementAt(0),rhs.elementAt(2))),1);
62             res.setElementAt(sub.sub(
63                     mul.mul(lhs.elementAt(0),rhs.elementAt(1)),
64                     mul.mul(lhs.elementAt(1),rhs.elementAt(0))),2);
65             return res;
66         }
67         else
68         {
69             return sub.sub(
70                 mul.mul(lhs.elementAt(0),rhs.elementAt(1)),
71                 mul.mul(lhs.elementAt(1),rhs.elementAt(0)));
72             
73         }
74     }
75 }
76
Popular Tags