gpt4 book ai didi

Java - 函数式浮点计算

转载 作者:行者123 更新时间:2023-12-02 07:56:00 27 4
gpt4 key购买 nike

由于浮点限制,我猜这里 smsm2 不相等:

double sm = -1.22 + (0.6027852837247973 + 0.8920332205475238);
double sm2 = -1.22 + 0.6027852837247973 + 0.8920332205475238;
System.out.println("sm = "+sm);
System.out.println("sm2 = "+sm2);
System.out.println("sm-sm2 = "+(sm-sm2));

结果是:

sm = 0.27481850427232124
sm2 = 0.27481850427232113
sm-sm2 = 1.1102230246251565E-16

我猜由于操作顺序,它不为零?

无论如何,在这种情况下我想问的是 - 如何拥有与此代码等效的代码:

double r2 = 0;
for(double o : ar){
r2+=o*2;
}
r2 -= k;

以功能风格(例如像这样,但由于这是第一次操作,我的输出有问题):

Arrays.stream(ar)
.map(o -> o*2)
.reduce(-k, Double::sum);

最佳答案

正如您在问题中提到的,操作顺序很重要。当您使用流时,无法保证执行顺序。除此之外,您的流方法还有另一个问题,那就是 identity 的值参数-k在你的情况下(我假设你想从结果中减去一些非零值)。 reduce(double identity, DoubleBinaryOperator accumulator)中的恒等值和累加器函数必须使得以下陈述始终为真:

accumulator.apply(identity, x) = x // for any value of x

有累加器Double::sum (与 (d1, d2) -> Double.sum(d1, d2) 相同)有效身份的唯一值为 0。

JavaDoc 引用:

double java.util.stream.DoubleStream.reduce(double identity, DoubleBinaryOperator op)

Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value. This is equivalent to:

double result = identity;
for (double element : this stream)
result = accumulator.applyAsDouble(result, element)
return result;

but is not constrained to execute sequentially. The identity value must be an identity for the accumulator function. This means that for all x, accumulator.apply(identity, x) is equal to x. The accumulator function must be an associative function.

This is a terminal operation.

你可以尝试这样的事情(正如@VLAZ建议的那样):

double calculate(double[] values, double k) {
return DoubleStream.of(values).map(d -> d * 2).reduce(0, Double::sum) - k;
}


更新

根据@LouisWasserman的建议,calculate可以通过替换 reduce(0, Double::sum) 来简化方法与 sum() :

double calculate(double[] values, double k) {
return DoubleStream.of(values).map(d -> d * 2).sum() - k;
}

关于Java - 函数式浮点计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58919868/

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