gpt4 book ai didi

java - Number 或 BigInteger 和 BigDecimal 中的错误(或者在这些的 API 文档中)?

转载 作者:行者123 更新时间:2023-12-03 06:01:28 35 4
gpt4 key购买 nike

根据 Number.longValue() 的规范,该方法应该...

Returns the value of the specified number as a long. This may involve rounding or truncation.

但是,BigInteger(和BigDecimal)会重写此方法并返回其表示的数字的整数部分的 64 个低位。例如,来自 BigInteger 的文档:

[...]if this BigInteger is too big to fit in a long, only the low-order 64 bits are returned.[...]

我声称“这可能涉及舍入或截断。”并没有说明该方法实际上应该返回什么,或者,实现或文档中存在错误。

你同意吗?还是我的推理有错误?

<小时/>

示例代码:

import java.math.BigInteger;
import static java.math.BigInteger.*;

public class Main {
public static void main(String[] args) {

BigInteger i = valueOf(Long.MAX_VALUE);

// Result: Long.MAX_VALUE, just as expected.
Number n1 = i;
System.out.println(n1 + " -> " + n1.longValue());

// I expect to get the "rounded" value Long.MAX_VALUE
Number n2 = i.add(ONE);
System.out.println(n2 + " -> " + n2.longValue());

// I expect to get the "rounded" value Long.MAX_VALUE
Number n3 = i.multiply(TEN);
System.out.println(n3 + " -> " + n3.longValue());
}
}

输出:

9223372036854775807 -> 9223372036854775807
9223372036854775808 -> -9223372036854775808
92233720368547758070 -> -10

最佳答案

BigInteger.longValue() 的文档继续:

Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign.

这重新定义(或澄清)了 Number.longValue() 定义的行为。这很好,尽管有时会产生误导。例如,java.util.Set 重新定义了 add 方法的行为(通过限制重复项)。如果您传递Collection,您可能期望它保存任何值,但具体实现已经重新定义了此行为。

更新:我检查了 Long.valueOf(Long.MAX_VALUE).intValue() 的行为方式。它打印-1。所以我认为对于 float 来说,“舍入或截断”只是一种可能性。否则,Number 类将转换方式完全留给实现者。所以是的 - 它没有透露任何信息。我不会说这有那么糟糕,但它肯定具有误导性。

关于java - Number 或 BigInteger 和 BigDecimal 中的错误(或者在这些的 API 文档中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4204133/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com