-4

I am making a program to calculate the Euclidean Distance of 4 values of Training Data with 4 values of Test Data. For KNN i need to find the Euclidean Distance which i programmed in Java and i am getting an incorrect answer from the result.

/**
 *
 *
 */
public class KNN {
double w1,x1,y1,z1;
double w2,x2,y2,z2;
  Scanner n=new Scanner(System.in);
////3 preset values of the Test Data///////
  void Test()
{  
    int x;
    System.out.println("Enter 1 for TD 1 2 for TD 2 and 3 for TD 3");
    x=n.nextInt();
    if(x==1){
    w2=89;
    x2=34;
    y2=27;
    z2=38;}
    else if(x==2)
    {
    w2=58;
    x2=87;
    y2=35;
    z2=38;}
    else if(x==3)
    {
    w2=34;
    x2=61;
    y2=49;
    z2=68;}
    }

//////Input values of Training Data/////
void input()
{

    System.out.println("Enter Feature 1 of Training Data ");
    w1=n.nextDouble();
    System.out.println("Enter Feature 2 of Training Data ");
    x1=n.nextDouble();
    System.out.println("Enter Feature 3 of Training Data ");
    y1=n.nextDouble();
    System.out.println("Enter Feature 4 of Training Data ");
    y1=n.nextDouble();

}

///////Formula for the Euclidean Distance for Training and Test data//////
double formula()
{  double r1,r2,r3,r4;
double r5;
r1=(w2-w1);
r2=(x2-x1);
r3=(y2-y1);
r4=(z2-z1);
r5=(r1*r1)+(r2*r2)+(r3*r3)+(r4*r4);
 System.out.println(r5);
    return Math.sqrt(r5) ;
}

The Answer i am getting for the Test Values which are in this case w1,x1,y1,z1 are 89,34,27 and 38 respectively and for the Training Data i am using 69,72,72 and 29 With the calculator i am getting the answer 62.84 but from the result of the code is giving me an answer of

Start program? 1 for yes and anything else for cancel
1
Enter 1 for TD 1 2 for TD 2 and 3 for TD 3
1
Enter Feature 1 of Training Data 
69
Enter Feature 2 of Training Data 
72
Enter Feature 3 of Training Data 
72
Enter Feature 4 of Training Data 
29
3292.0
57.37595315112421
Enter 1 for TD 1 2 for TD 2 and 3 for TD 3

Mind you this program is for completing an assignment so i made it in 5 minutes. So go easy on me about the way it is formated

Jee Whizz
  • 21
  • 1
  • 6

1 Answers1

1

Your input method is wrongly assigning y1 twice, instead of assigning the last read value to z1.

Hiery Nomus
  • 17,429
  • 2
  • 41
  • 37