Inversion sum is not correct using Stream.reduce

淺唱寂寞╮ 提交于 2019-12-07 21:24:56

问题


Inversion sum is not correct using Stream.reduce, what is going wrong here ?

double[] array = {1.0, 2.0};
double iunversionSum = Arrays.stream(array).reduce(0.0, (a, b) -> Double.sum(1.0 / a, 1.0 / b));

output is .5 but expected is 1.5 (1/1 + 1/2)


回答1:


I think using map() it could be simplier.

double inversionSum = Arrays.stream(arr).map(val -> 1 / val).sum();



回答2:


The error in your reduce is: Double.sum(1.0 / a, 1.0 / b), starting the series with 0.0. Now check why your outcome is .5.

Use Double.sum(a, 1.0 / b), if you want to use reduce.



来源:https://stackoverflow.com/questions/54144110/inversion-sum-is-not-correct-using-stream-reduce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!