1

In scheme I can do this:

#;> (/ 1 3)
1/3
#;> (exact->inexact (/ 1 3))
0.3333333333333333

This is called an "exact division".

I was playing with BigDecimal in Java and figured out that you can use its .divide() function to make exact divisions, but this function throws an ArithmeticException if the division is not exact. You can use other similar functions to specify how you want to round, but if I just don't want to round (equivalent in Scheme exact->inexact function).

Is that possible using pure Java? Or maybe a library?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Felipe
  • 16,649
  • 11
  • 68
  • 92

3 Answers3

2

Clojure has rational numbers:

%> clojure
Clojure 1.0.0-
user=> (/ 1 3)
1/3

No matter if you think making your application in Clojure is a good idea or not, you could always implement the math in Clojure or even use Cojure macroes to it's full extent in order to have more expressive power and compile the script. One namespace is one class and it's easy to import and use in Java classes. The other way around is the most common though since Clojure is almost nothing without the Java class library. They mix and match both ways.

Sylwester
  • 47,942
  • 4
  • 47
  • 79
1

There is a library which can do this, yes: apfloat, and more precisely its Aprational class. See also AprationalMath.

fge
  • 119,121
  • 33
  • 254
  • 329
1

If you want to treat something like 1/3 directly as Java code, this will always be evaluated one way or another in Java and treated like one of the primitive numerical types (e.g. double, depending on which types you use).

If you wanted to keep 1/3 as a fraction, you would need to have a library to model it as a fraction. Essentially, you're looking at a tool capable of doing symbolic maths in Java. You might not need a very powerful one (e.g. you might not need something capable of differentiation), but it will at least need to be able to represent fractions, and presumably do some basic operations and simplifications with them (I guess that's what you're after).

Apache Commons Maths (Fractions section) should be of interest. You might also be interested in some of the libraries referenced in this question: https://stackoverflow.com/q/2574949/372643

Unfortunately, Java doesn't allow for operator overloading, so writing mathematical code in Java can be quite tedious. In general, you'll have to input your mathematical expressions as text and expect the library to model the expression with its own classes more or less transparently, or you'll have to use methods on objects like add, mult, ...

If you have a lot of math to do in a Java environment, it might be worth investigating what other languages that run on the JVM have to offer, such as Jython or Scala.

Community
  • 1
  • 1
Bruno
  • 119,590
  • 31
  • 270
  • 376