KickJava   Java API By Example, From Geeks To Geeks.

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


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 package org.nfunk.jep.function;
10
11 import java.lang.Math JavaDoc;
12 import java.util.*;
13 import org.nfunk.jep.*;
14 import org.nfunk.jep.type.*;
15
16 public class SquareRoot extends PostfixMathCommand
17 {
18     public SquareRoot() {
19         numberOfParameters = 1;
20     }
21     
22     /**
23      * Applies the function to the parameters on the stack.
24      */

25     public void run(Stack inStack) throws ParseException {
26             
27         checkStack(inStack);// check the stack
28
Object JavaDoc param = inStack.pop();
29         inStack.push(sqrt(param));//push the result on the inStack
30
return;
31     }
32
33     /**
34      * Calculates the square root of the parameter. The parameter must
35      * either be of type Double or Complex.
36      *
37      * @return The square root of the parameter.
38      */

39     public Object JavaDoc sqrt(Object JavaDoc param) throws ParseException
40     {
41         if (param instanceof Complex)
42             return ((Complex)param).sqrt();
43         if (param instanceof Number JavaDoc) {
44             double value = ((Number JavaDoc)param).doubleValue();
45             
46             // a value less than 0 will produce a complex result
47
if (value < 0.0) {
48                 return (new Complex(value).sqrt());
49             } else {
50                 return new Double JavaDoc(Math.sqrt(value));
51             }
52         }
53
54         throw new ParseException("Invalid parameter type");
55     }
56 }
57
Popular Tags