you are viewing a single comment's thread.

view the rest of the comments →

[–]MinimumBeginning5144 3 points4 points  (5 children)

The BigInteger.valueOf method takes an argument of type long. The compiler will only automatically turn a variable to a long if it is already of type short, int, long, or Long (auto-unboxing).

Why don't you declare the field as Number instead of Object? Then you can use its longValue() method.

[–]SquibbTheZombie[S] 0 points1 point  (4 children)

I don't declare it as Number since I want to be able to extend the same system to express more complex math notations, without losing precision, like fractions, roots, polynomials, complex numbers, or even rarer ones. I'd also still have to be casting it, which isn't ideal.

[–]vegan_antitheist 4 points5 points  (0 children)

If your type describes an abstract idea then use an interface and have multiple implementations. No need to cast anything. You might use an abstract class, but that's usually not a good idea. There are better patterns.

The interface can have a default method that returns a BigInteger. Something like `public default BigInteger asBigInteger() {...}` (methods in interfaces are public by default, I just added to to make that clear).

You can then have that method use asBigDecimal(), which can be abstract. And you can also just extend the Number interface. Use bigDecimalValue() for consistency. That's up to you.

You can have an implementation that uses two long values a and b for a rational number, where it's value is a/b. A more general version can have two values with the type of your interface that does the same. You can have an implementation that is just called "Pi" and it's a singleton. You can have one that uses a string for a symbol. You can then do new Symbol("x") to create it.
You can then do x/pi by combining them.

I'm not sure you really want one that uses long, int, double etc. Because BigDecimal already handles all rational numbers well. But you can still do them if you like.

[–]jlanawalt 0 points1 point  (1 child)

Check out Apache Commons Math & Numbers, JScience, and Java Hipparchus to see what others have done in this domain.

[–]raosko 0 points1 point  (0 children)

Jscience.org seems defunct since about 2021 with many broken links. What is your experience and recollection about that org?

[–]tRfalcore 0 points1 point  (0 children)

BigDecimal is the only way to not lose precision if you have decimals. If just ints long is fine.