我不知道该如何解决。 为什么说运营商未定义,我该如何解决?
我的猜测是它是由于括号[和]而引起的,但是在删除它们时,它表示无法将int转换为double。
public static void main(String[] args)
{
double value1 = 5.0;
double[] valuearray = {1,2,3};
int p = 2;
System.out.print("The L" + p + "-distance between: " + value1 + " and " + valuearray + " = " + getLpDistance(value1, valuearray, p));
}
public static Double getLpDistance(double value1, double[] valuearray, int p) {
int d = 1;
double tmp = 0;
for (int i = 1; i <= d; i++) {
tmp += Math.pow(Math.abs(value1 - valuearray), p);
}
return Math.pow(tmp, 1.0 / p);
}
答案 0 :(得分:0)
您的猜测是正确的:您不能从数组(valuearray
)中减去双精度数组(value1
)。
要返回valuearray
的每个元素的减法,您必须这样做:
for (int i = 1; i <= d; i++) {
tmp += Math.pow(Math.abs(value1 - valuearray[i]), p);
}
答案 1 :(得分:0)
如果只想测量距离,您的代码看起来就很接近了。我在代码中做了一些更改。危险点是当您将p设置为0时,代码将中断。假设您必须将其作为特殊情况处理。
以下代码供您参考。我已添加评论供您参考。
public class LPDistance {
public static void main(String[] args)
{
double value1 = 5.0;
double[] valuearray = {1,2,3};
//when you have to deal with p = 0, you have to add some conditions in your code to deal with that...
int p = 2;
System.out.print("The L" + p + "-distance between: " + value1 + " and " + printArray(valuearray) + " = " + getLpDistance(value1, valuearray, p));
}
private static String printArray(double[] valuearray) {
//utility function to print an array
String arrayPrint = "[ ";
for(int i=0;i<valuearray.length-1;i++)
arrayPrint+=valuearray[i]+", ";
arrayPrint+=valuearray[valuearray.length-1]+" ]";
return arrayPrint;
}
public static Double getLpDistance(double value1, double[] valuearray, int p) {
// int d = 1; don't need to set this if you want to go through all the array elements
double tmp = 0;
//updated the loop parameters to traverse through the loop
for (int i = 0; i < valuearray.length; i++) {
tmp += Math.pow(Math.abs(value1 - valuearray[i]), 2); // if it is distance, power will be always 2
}
//if you will pass p=0, below code will fail.
return Math.pow(tmp, 1.0 / p);
}
}