2

I'm trying to create a number class which can hold values from 4.9E-324e-1.7976931348623157E308 to 1.7976931348623157E308e1.7976931348623157E308 in both signs. (yes, the exponent is also a double)

My number class is in base 2.

I have all the arithmetic working, but I'm having trouble trying to display it as a string in the format ...#####.#####....

This is what I've come up with.

@Nonnull
    public String toReadableString(@Nonnull MathContext context) {
        try {
            final BigDecimal mantissa = BigDecimal.valueOf(y);
            final BigDecimal exponentiation = BigDecimal.valueOf(2).pow((int) x, context);
            // The above line throws an ArithmeticException if magnitude(x) > 999999999
            // This is defined in BigDecimal, and I can't change the limit

            final BigDecimal result = mantissa.multiply(exponentiation);

            return result.toPlainString();
        } catch (final ArithmeticException e) {
            return "OUT_OF_DISPLAYABLE_RANGE";
        }
    }

I've tried searching for other methods of converting base 2 to base 10, but every method I could find involves actually calculating the value as a double, which would obviously not work for most values of this number class.

Summary

I need a function toReadableString() : String which can reliably convert base 2 scientific notation in the form of 2^double * double for an arbitrary n number of decimal points.

Any help would be great, even if it's not a complete solution.

For reference, here's the structure of my number class.

// This extends Vector2 to use all the features provided by the vector class
public class RealNumber extends Vector2 implements Comparable<RealNumber> {
    public RealNumber(double val);
    public RealNumber(double exponent, double mantissa);

    public final double exponent();
    public final double mantissa();

    // Code ommitted

    public String toReadableString(MathContext context); // Body defined above
}

I know this is very impractical and abstract. I personally like that kind of stuff, and this is a purely personal project which I'm doing for fun.

I've tried:

  • Converting exponent and mantissa to BigDecimal to calculate the value (BigDecimal.pow(int) causes a problem)
  • The current approach
  • Just using double (of course it doesn't work)
  • Iterating through each digit and adding the value to a BigDecimal (maybe there was an error in my code, but didn't work)
LXIV
  • 21
  • 3
  • 2
    It doesn't really help that you don't say what this mysterious "problem" is – g00se Aug 14 '23 at 07:55
  • @g00se BigDecimal#pow(int) doesn't allow the use of the full integer range. And even if it did, it still wouldb't be enough coverage for by double exponent, even if I gave up the accuracy of double. – LXIV Aug 14 '23 at 08:27
  • Raising 2 to the xth power can be done with `new BigDecimal(BigInteger.ONE.shiftLeft(x))`. I’m not sure if that helps. – VGR Aug 14 '23 at 15:39

0 Answers0