我想,以确定double 机器精度在Java中,使用它是最小的可表示的定义double值,x这样1.0 + x != 1.0,就像在C/C++.根据维基百科,这台机器epsilon等于2^-52(52是double尾数位数 - 1).
我的实现使用了这个Math.ulp()函数:
double eps = Math.ulp(1.0);
System.out.println("eps = " + eps);
System.out.println("eps == 2^-52? " + (eps == Math.pow(2, -52)));
Run Code Online (Sandbox Code Playgroud)
结果是我的预期:
eps = 2.220446049250313E-16
eps == 2^-52? true
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.不过,如果我检查给定的eps确实是最小的 x这样1.0 + x != 1.0,似乎有一个较小的一个,又名先前 double根据价值Math.nextAfter():
double epsPred = Math.nextAfter(eps, Double.NEGATIVE_INFINITY);
System.out.println("epsPred = " + epsPred);
System.out.println("epsPred < eps? " …Run Code Online (Sandbox Code Playgroud) 这一切都始于一个非常基本的问题:给定一个char——或者更确切地说,一个整数代码点,请参阅CharacterAPI——,返回其 UTF-8 编码所需的字节数。然而,我在这个无辜的小问题上花费的时间越多,它就变得越令人困惑。
我的第一个方法是:
int getUtf8ByteCount_stdlib(int codePoint) {
int[] codePoints = { codePoint };
String string = new String(codePoints, 0, 1);
byte[] bytes = string.getBytes(StandardCharsets.UTF_8);
return bytes.length;
}
Run Code Online (Sandbox Code Playgroud)
或者对于那些喜欢它的人:
int getUtf8ByteCount_obfuscated(int codePoint) {
return new String(new int[] { codePoint }, 0, 1).getBytes(StandardCharsets.UTF_8).length;
}
Run Code Online (Sandbox Code Playgroud)
然后,为了简单性和效率,我创建了另一个版本(基于UTF-8 维基百科文章):
int getUtf8ByteCount_handRolled(int codePoint) {
if (codePoint > 0x7FFFFFFF) {
throw new IllegalArgumentException("invalid UTF-8 code point");
}
return codePoint <= 0x7F? 1
: codePoint <= 0x7FF? 2
: codePoint <= …Run Code Online (Sandbox Code Playgroud) 是否有任何无分支或类似的黑客用于将整数钳位到0到255的间隔,或者是一个双倍到0.0到1.0的间隔?(两个范围都是封闭的,即端点是包含的.)
我正在使用明显的最小 - 最大检查:
int value = (value < 0? 0 : value > 255? 255 : value);
Run Code Online (Sandbox Code Playgroud)
但有没有办法让它更快 - 类似于"模"钳value & 255?有没有办法用浮点做类似的事情?
我正在寻找便携式解决方案,所以最好不要使用CPU/GPU特定的东西.
language-agnostic math floating-point bit-manipulation integer-arithmetic