在java中不使用循环添加双[]数组的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4094644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding the elements of a double[] array without using a loop in java
提问by Namalak
I have a double[]of huge size. (Ex : Eg.double[] array = new double[] {2.0, 3.1, 4.2, 8.9, 10.11, ........}
)
我有一个巨大的double[]。(例如:例如。double[] array = new double[] {2.0, 3.1, 4.2, 8.9, 10.11, ........}
)
I want to get the sum of all the elementsof that array at once. (Without using a loop).
我想一次获得该数组所有元素的总和。(不使用循环)。
Do you have any idea to do this?
你有什么想法要这样做吗?
采纳答案by Andreas Dolk
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).
不,您不能一步计算一组值的总和。即使有提供 sum 函数的 API 方法或某个库,它也会在内部使用循环。求和算法的复杂度为 O(n)(对于单个 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).
出路可能是使用并行计算,但这是回答您的问题的理论方法。您至少需要与数组单元一样多的 CPU 来计算步骤中的总和。(或者一个虚构的 CPU,其 FP 寄存器与数组值一样多)。
Before you start looking at API's of Java or other libraries:
在开始查看 Java 或其他库的 API 之前:
public static double sum(double...values) {
double result = 0;
for (double value:values)
result += value;
return result;
}
Usage:
用法:
double sum = sum(array); // this is in your main code -> no loop (visible)
回答by paxdiablo
Yes, use a loop. That's what they're for. Hundreds of elements is a piddling little size for an array and will take almost no time to process.
是的,使用循环。这就是他们的目的。数百个元素对于一个数组来说是一个微不足道的小尺寸,几乎不需要时间来处理。
回答by Abhinav Sarkar
First of all, 'hundreds' is not 'huge' ('millions' is) and second, adding the elements without looping is not possible unless you have some prior information about the elements (like if they are a part of a particular series).
首先,“数百”不是“巨大”(“百万”是),其次,除非您有关于元素的一些先验信息(例如它们是特定系列的一部分),否则不可能在不循环的情况下添加元素.
回答by Ben Flynn
Anyone who has an actually huge array of doubles might look up cern.colt.list.AbstractDoubleList, which is built to optimize operations like adding (elements).
任何拥有大量双精度数组的人都可以查找cern.colt.list.AbstractDoubleList,它旨在优化添加(元素)等操作。
As others have said, if you want the summation of all elements in your array, you should write a loop.
正如其他人所说,如果您想对数组中的所有元素求和,则应该编写一个循环。
回答by Stephen C
A loop is the simplest and most efficient way to do things like summing the elements of an array or collection in Java.
循环是在 Java 中对数组或集合的元素求和之类的最简单、最有效的方法。
There are ways to sum arrays that don't involve explicit loops, but they involve using simulatedhigher order functions, and they are complicated and ugly when written in Java. (And they are expensive and use loops under the hood.)
有一些方法可以不涉及显式循环对数组求和,但它们涉及使用模拟的高阶函数,并且用 Java 编写时它们既复杂又丑陋。(而且它们很昂贵并且在引擎盖下使用循环。)
Java is not a functional programming language. If you want / need to do functional programming on the Java platform, use Scala or Clojure.
Java 不是函数式编程语言。如果您想/需要在 Java 平台上进行函数式编程,请使用 Scala 或 Clojure。
回答by ZeissS
Looping is the simplest way for this, but since you asked for a different one:
循环是最简单的方法,但由于您要求使用不同的方法:
Recursion:
递归:
double sumResult = sum(data, 0, 0);
double sum(double [] d, int sum, int index) {
if ( index > d.length ) return sum;
else return sum(d, sum + d[index], index+1);
}
I haven't tested that, but it should work somewhere along the above.
我没有测试过,但它应该在上面的某个地方工作。
EDIT: It is not recommended to use such a construct, since for huge array you may hit the StackOverflowException very fast.
编辑:不建议使用这样的构造,因为对于巨大的数组,您可能会非常快地遇到 StackOverflowException。
回答by GuiltyBystander
If you're really concerned with accuracy, a simple loop might cause some problems. Doubles do not contain arbitrary precision. Here's a simple example to show the flaw of just using a loop.
如果您真的很关心准确性,一个简单的循环可能会导致一些问题。双精度不包含任意精度。这是一个简单的例子,展示了只使用循环的缺陷。
float f = 0;
for(int i = 0; i < 1000*1000*1000; ++i){
++f;
}
System.out.println(f);
We would hope that f would be 1 billion, or 1.0E9, but instead we get 1.6777216E7. This is because the float can only hold about 6-7 digits of precision. A double can hold about 16-17 digits of precision which means it is less likely to have an issue, but it doesn't solve the problem.
我们希望 f 是 10 亿,或 1.0E9,但我们得到的是 1.6777216E7。这是因为浮点数只能保持大约 6-7 位的精度。double 可以保存大约 16-17 位的精度,这意味着它不太可能出现问题,但它并不能解决问题。
To work around this, we need to not add two numbers when there is a large magnitude difference between them. This can simply be done using a PriorityQueue. We'll take out the first 2 numbers, add them, then put them back into the queue. When the queue only has 1 number left, we return it.
为了解决这个问题,当两个数字之间存在很大的差异时,我们不需要将它们相加。这可以简单地使用 PriorityQueue 来完成。我们将取出前 2 个数字,将它们相加,然后将它们放回队列中。当队列只剩下 1 个号码时,我们返回它。
public static double queueSum(double[] da){
PriorityQueue<Double> pq = new PriorityQueue<Double>(da.length);
for(double d : da)
pq.add(d);
while(pq.size() > 1)
pq.add(pq.poll() + pq.poll());
return pq.poll();
}
Of course accuracy does come at the cost of time. This goes from the loop sum's O(n) to a O(n lg(n)) not to mention the overhead of the objects involved.
当然,准确性确实是以时间为代价的。这从循环总和的 O(n) 到 O(n lg(n)) 更不用说所涉及对象的开销。
Because doubles have much more precision than a float, you probably won't need to use this unless you have a huge number of doubles (millions/billions) and/or you have a large difference in magnitudes between your numbers.
因为双精度比浮点精度高得多,除非您有大量双精度(百万/十亿)和/或数字之间的量级差异很大,否则您可能不需要使用它。
Edit: If all the numbers have approximately the same magnitude, this code will help avoid the problem as well as maintain O(n) time. If there is a large magnitude difference between two samples or the numbers are distributed in a fashion that could cause a large magnitude difference, it could suffer the same problems as before.
编辑:如果所有数字的大小大致相同,则此代码将有助于避免问题并保持 O(n) 时间。如果两个样本之间存在较大的幅度差异,或者数字的分布方式可能会导致较大的幅度差异,则可能会遇到与以前相同的问题。
public static double treeSum(double[] da){
double[] dc = da.clone();
int len = dc.length;
while(len > 1){
len = (len + 1) / 2;
for(int i = 0; i < len; ++i)
dc[i] += dc[i + len];
dc[len] = 0;
}
return dc[0];
}
回答by Carlo
If your array is assigned to a DoubleMatrix1D object in cern.colt.matrix library you can use the zSum() method and it will return the sum of all elements in your array without having to loop
如果您的数组被分配给 cern.colt.matrix 库中的 DoubleMatrix1D 对象,您可以使用 zSum() 方法,它将返回数组中所有元素的总和,而无需循环
your_sum=your_array.zSum()
your_sum=your_array.zSum()
回答by Roland S. Wilson
You need to create a nested class inside of the function and use recursion inside of the nested class to do the addition:
您需要在函数内部创建一个嵌套类并在嵌套类内部使用递归来进行添加:
public double sumArrayNoLoop(double[] v){
class compute {
double total = 0.0;
public void sumArray(double[] v,int offset){
if((offset - 1) < 0) return;
if(offset > (v.length - 1)) offset = v.length;
total += v[offset - 1];
sumArray(v,offset - 1);
}
}
compute c = new compute();
c.sumArray(v, v.length);
return c.total;
}
I
一世
回答by Pradip Wawge
I would prefer the following approach.
我更喜欢以下方法。
package rfcampusdata;
public class TestClass {
public static void main(String[] args) {
String str = "1,2,3,4,5";
String[] arr = str.split(",");
int length = arr.length;
System.out.println(sum(length, arr));
}
static Double temp = new Double(0);
public static Double sum(int length, String[] arr) {
int length_m = length - 1;
String[] arr_m = arr;
temp += Double.parseDouble(arr[length_m]);
if (length_m != 0) {
sum(length_m, arr_m);
} else {
// temp += Integer.parseInt(arr[0]);
// System.out.println(temp);
}
return temp;
}