2

How do I store a big irrational number like pi or 7^(1/2)? Preferably I should be able to store a large number of digits (1000+) but not necessary.

IHirs
  • 29
  • 1
  • 6
    You cannot store an irrational number precisely as a `BigDecimal`. Irrationals do not have a finite decimal representation. You can store an approximation of one. What have you tried? – khelwood Mar 16 '19 at 00:20
  • I have tried MathContext then .round() – IHirs Mar 16 '19 at 00:32
  • 1
    Perhaps you would like to post [the code you tried](https://stackoverflow.com/help/mcve) and describe what problem you had with it. – khelwood Mar 16 '19 at 00:35
  • Is the question "how to compute a square root or pi to a high precision?" Storing such a number is no different from storing any other number. See for example here for how to compute a square root https://stackoverflow.com/q/13649703/318758 – Joni Mar 16 '19 at 01:08

1 Answers1

2

You can not store an irrational number, because its endless. Beside that you can store a BigDecimal with a large, but limited number of digits as plain String value. To set the precision of your number you can use BigDecimal.setScale(). This takes the number of digits and a RoundingMode.

Here is an example:

BigDecimal irrational = ...
BigDecimal result = irrational.setScale(1000, RoundingMode.HALF_UP);
FileUtils.writeStringToFile(new File("test.txt"), result.toPlainString());

I would recommend using BigDecimal.toPlainString() instead of BigDecimal.toString().

From the docs:

toPlainString(): Returns a string representation of this BigDecimal without an exponent field.

toString(): Returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.

Create a new BigDecimal from the file you can just pass the String value to the constructor:

BigDecimal number = new BigDecimal(FileUtils.readFileToString(new File("test.txt")));

You also can use this to store the number in a database, or wherever you want. Just store it as String value.

Community
  • 1
  • 1
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
  • Rounding makes the number rational. – Makoto Apr 29 '19 at 20:48
  • @Makoto Of course it does, as I wrote in my post: _Of course only a limited number of digits._ You can not store an endless number. But you can set the precision. – Samuel Philipp Apr 29 '19 at 20:49
  • You may wish to rephrase your opening sentence then. I was given the impression that I could store an irrational number in a `BigDecimal`. – Makoto Apr 29 '19 at 20:49
  • @Makoto Yes, thanks for that hint. This was not quite clear at the beginning. I updated my post. Hope it is more clear now. – Samuel Philipp Apr 29 '19 at 20:53