Using Abs function

36 views
Skip to first unread message

Max

unread,
Nov 14, 2011, 3:38:10 PM11/14/11
to Jep Java Users
Hello,

I'm using Jep 3.4. I'd like to use the abs() function

I tried this code which is OK :

Jep jep = new Jep();
jep.addVariable("x",new BigDecimal(4));
jep.parse("sqrt(x)");
Object result = jep.evaluate();

but this one throws an exception :

Jep jep2 = new Jep();
jep2.addVariable("x",new BigDecimal(4));
jep2.parse("abs(x)");
Object result2 = jep2.evaluate();

Can you explain me why ?

Thanks for any help
Max

Richard Morris

unread,
Nov 14, 2011, 4:19:17 PM11/14/11
to jep-...@googlegroups.com
Hi Max,

By default the abs function only works for normal Double, Integer not
BigDecimals. Firstly I'd question wether you really want BigDecimal,
these have uses for financial calculations but are not particularly
useful for most other applications.

Jep does not supply many functions for BigDecimals, only the standard
mathematical operations and comparisons, most of the other ones don't
make a lot of sense for decimals. Abs is one which would be useful,
and we'll think about including it in the next release.

In the meantime you can create your own PFMC to implement abs for
BigDecimals. The following is a working function. To use this you
would need to initialise things like

BigDecComponents compSet = new
BigDecComponents(MathContext.DECIMAL64, true);
jep = new Jep(compSet);
jep.getFunctionTable().addFunction("abs",new BDAbs());


Hope that helps

Rich

package com.singularsys.jep.bigdecimal.functions;

import java.math.BigDecimal;
import com.singularsys.jep.EvaluationException;

/**
* Absolute value function for BigDecimals, Double and other Number types.
* Uses {@link BigDecimal#abs()} for BigDecimals and {@link
com.singularsys.jep.functions.Abs} for other types.
* @author Richard Morris
*
*/
public class BDAbs extends com.singularsys.jep.functions.Abs
{
private static final long serialVersionUID = 350L;

@Override
public Object eval(Object arg) throws EvaluationException {
return abs(arg);
}

@Override
public Object abs(Object param)
throws EvaluationException
{
if (param instanceof BigDecimal)
{
return ((BigDecimal)param).abs();
}
return super.abs(param);
}


}

> --
> You received this message because you are subscribed to the Google Groups "Jep Java Users" group.
> To post to this group, send email to jep-...@googlegroups.com.
> To unsubscribe from this group, send email to jep-users+...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/jep-users?hl=en.
>
>

Reply all
Reply to author
Forward
0 new messages