如何存储像 pi 或 7^(1/2)
这样的大无理数?最好我应该能够存储大量数字(1000+),但不是必需的。
最佳答案
你不能存储无理数,因为它是无穷无尽的。除此之外,您还可以存储 BigDecimal
具有大量但有限数量的数字作为纯字符串值。要设置数字的精度,您可以使用 BigDecimal.setScale()
。这需要位数和 RoundingMode
.
这是一个例子:
BigDecimal irrational = ...
BigDecimal result = irrational.setScale(1000, RoundingMode.HALF_UP);
FileUtils.writeStringToFile(new File("test.txt"), result.toPlainString());
我建议使用BigDecimal.toPlainString()
而不是BigDecimal.toString()
.
来自文档:
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.
从文件创建一个新的 BigDecimal
,您只需将 String 值传递给构造函数即可:
BigDecimal number = new BigDecimal(FileUtils.readFileToString(new File("test.txt")));
您还可以使用它将号码存储在数据库中或任何您想要的位置。只需将其存储为字符串值即可。
关于java - 如何存储无理数 BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192239/