Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BigDecimal trigonometric methods

I am developing a mathematical parser which is able to evaluate String like '5+b*sqrt(c^2)'. I am using ANTLR for the parsing and make good progress. Now I fell over the Java class BigDecimal and thought: hey, why not thinking about precision here.

My problem is that the Java API does not provide trigonometric methods for BigDecimals like java.lang.Math. Do you know if there are any good math libraries like Apache Commons out there that deal with this problem?

The other questions is how to realize the power method so that I can calculate 4.9 ^ 1.4 with BigDecimals. Is this possible?

A book request about numerical computing is also appreciated.

like image 928
Marco Avatar asked Jan 31 '10 21:01

Marco


People also ask

How do you find the trigonometric value of an angle in Java?

Math. sin() Method : is an inbuilt method which returns the sine of the value passed as an argument. The value passed in this function should be in radians.

Is BigDecimal more precise than double?

I know that BigDecimal is more precise than double and you should use the former for calculations.

Which method is used to return the trigonometric cosine value of a given double value?

lang. Math. cos() returns the trigonometric cosine of an angle. If the argument is NaN or an infinity, then the result returned is NaN.

How do you find the sin of a number in Java?

sin() returns the trigonometry sine of an angle in between 0.0 and pi. If the argument is NaN or infinity, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument.


3 Answers

ApFloat is a library which contains arbitrary-precision approximations of trigometric functions and non-integer powers both; however, it uses its own internal representations, rather than BigDecimal and BigInteger. I haven't used it before, so I can't vouch for its correctness or performance characteristics, but the api seems fairly complete.

like image 182
Scott Fines Avatar answered Oct 15 '22 09:10

Scott Fines


BigDecimal does not provide these methods because BigDecimal models a rational number. Trigonometric functions, square roots and powers to non-integers (which I guess includes square roots) all generate irrational numbers.

These can be approximated with an arbitrary-precision number but the exact value can't be stored in a BigDecimal. It's not really what they're for. If you're approximating something anyway, you may as well just use a double.

like image 34
cletus Avatar answered Oct 15 '22 11:10

cletus


The big-math library provides all the standard advanced mathematical functions (pow, sqrt, log, sin, ...) for BigDecimal.

https://github.com/eobermuhlner/big-math

like image 21
Eric Obermühlner Avatar answered Oct 15 '22 10:10

Eric Obermühlner