Java和一个公式
我正在基于以下关联公式实现一个java方法:Java和一个公式,java,Java,我正在基于以下关联公式实现一个java方法: (f * g)[n] = ∑ f[n+m] * g[m], the lower bound of the summation is m = 0, and the upper bound is M - 1, where f is an array of size N and g is an array of size M. (f * g)[n] is an array of size N - M + 1 例如,如果我们有这些数组: f =
(f * g)[n] = ∑ f[n+m] * g[m],
the lower bound of the summation
is m = 0, and the upper bound is M - 1,
where f is an array of size N
and g is an array of size M.
(f * g)[n] is an array of size N - M + 1
例如,如果我们有这些数组:
f = {1, 2, 3, 4}, g = {10, 20}
The result is this array:
(f * g)[n] = {1(10) + 2(20), 2(10) + 3(20), 3(10) + 4(20)}
= **{50, 80, 110}**
我需要做的是将其转换为Java代码。我首先尝试为这个例子编写代码,然后提出一个更一般的情况。不幸的是,我被一些Java语法卡住了。这就是我目前拥有的:
public static void main(String[] args) {
double[] array1 = new double[] {1, 2, 3, 4, 5};
double[] array2 = new double[] {10, 20};
double[] array3 = new double[3];
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
double pos = array1[i];
double multiply = pos * array2[j];
array3[i]= pos * multiply;
}
}
System.out.print(Arrays.toString(array3));
}
基本上,我要做的是将乘法存储在array3的第一个索引中。然后,随着循环的进行,将其存储到第二个和第三个索引中。我知道我做错了,但我不确定如何实现它,第三个for循环似乎令人困惑且不切实际(我甚至不确定它是否有效)。谢谢大家! 您没有将输出数组设置为正确的长度,它需要根据两个输入长度(每个N-M+1)进行计算,而不是硬编码为三。[尽管我注意到,在你更新的问题中,3实际上是正确的数字] 这也是您必须进行的外部迭代次数。您的越界异常是由您从
0.开始的迭代引起的。。N-1
不考虑M
您也没有实际执行任何求和。您应该将array3[i]
设置为零,作为第一个循环[*]中的第一个操作,然后在内部循环中添加乘法项
static double[] array_product(double[] a, double[] b) {
int n = a.length - b.length + 1;
double[] result = new double[n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < b.length; ++j) {
result[i] += a[i + j] * b[j];
}
}
return result;
}
public static void main(String[] args) {
double[] array1 = new double[] {1, 2, 3, 4};
double[] array2 = new double[] {10, 20};
double[] result = array_product(array1, array2);
System.out.print(Arrays.toString(result));
}
静态双[]数组\u乘积(双[]a,双[]b){
int n=a.长度-b.长度+1;
双精度[]结果=新双精度[n];
对于(int i=0;i
[*]尽管Java语言规范保证将新数组设置为0.0,但为了代码的清晰性和代码被移植到一种无法保证的语言中,显式地这样做并不是一个坏主意。当询问您遇到的错误时,始终读取并发布错误。array3有3个元素。我从0到5。这怎么可能?在我看来,
array3
的元素数应该与array1
的元素数相同(即5)。不清楚为什么在示例中只进行了三次求和。错误为:“线程中的异常”main“java.lang.ArrayIndexOutOfBoundsException:3”。所以,您试图访问一个数组的无效索引,这个无效索引是3。完整错误还精确地告诉您该错误发生的位置:在array3[i]=pos*multiply行代码>。现在,为什么它会抛出这样一个错误?因为它试图访问array3的索引3,其长度为3(因此其最后一个有效索引为2)。为什么它要访问元素3,因为我从包含的0变为包含的5(数组1的长度)。当你阅读错误信息时,一切都变得简单了。你需要存储5个值。但是你用的是3个元素的数组?使用5个元素的数组不是很合乎逻辑吗?
static double[] array_product(double[] a, double[] b) {
int n = a.length - b.length + 1;
double[] result = new double[n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < b.length; ++j) {
result[i] += a[i + j] * b[j];
}
}
return result;
}
public static void main(String[] args) {
double[] array1 = new double[] {1, 2, 3, 4};
double[] array2 = new double[] {10, 20};
double[] result = array_product(array1, array2);
System.out.print(Arrays.toString(result));
}