在不使用java中的循环的情况下添加double []数组的元素 [英] Adding the elements of a double[] array without using a loop in java

查看:132
本文介绍了在不使用java中的循环的情况下添加double []数组的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个巨大的 double [] 。 (例如:<。code> double [] array = new double [] {2.0,3.1,4.2,8.9,10.11,........} )

I have a double[] of huge size. (Ex : Eg.double[] array = new double[] {2.0, 3.1, 4.2, 8.9, 10.11, ........})

我希望一次获得该数组的所有元素的总和。 (不使用循环)

你有任何想法吗?

推荐答案

不,您无法在一个步骤中计算值列表的总和。即使有一个API方法或某个提供sum函数的库,它也会在内部使用循环。求和算法的复杂性是O(n)(对于单个CPU)。

No, you can't calculate the sum of a list of values in one step. Even if there was an API method or some library that offered a sum function, it would use loops internally. The complexity of the sum algorithm is O(n) (for single CPUs).

一种出路可能是使用并行计算,但这是回答你的问题的理论方法。您至少需要与阵列单元一样多的CPU来计算步骤中的总和。 (或者一个具有与数组值一样多的FP寄存器的虚构CPU)。

A way out could be using parallel computing, but that's a theoretical approach to answer your question. You'd need at least as many CPUs as array cells to calculate the sum in on step. (Or one fictional CPU with as many FP registers as array values).

在开始查看Java的API之前或其他图书馆:

Before you start looking at API's of Java or other libraries:

 public static double sum(double...values) {
   double result = 0;
   for (double value:values)
     result += value;
   return result;
 }

用法:

 double sum = sum(array);  // this is in your main code -> no loop (visible)

这篇关于在不使用java中的循环的情况下添加double []数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆