Search code examples
javafloating-pointprocessing

How to prevent rounding to zero in Java


I'm working on a Processing sketch that emulates the windmill animation shown in this video: 3Blue1Brown Windmill Problem However I'm having an issue where my float values get rounded to zero when they shouldn't. For example, I could have the line:float ratio= (520-581)/(158-87) this should give the result of -0.859 but instead it just gives 0.0. I know floats generally have a certain amount of inaccuracy due to the nature of how they work, but this seems extreme. What am I doing wrong, and how can I fix it?

Here's the full code snippet for those who are interested:

void detectCollision(ArrayList<Point> points){
for(Point point : points){
  int x1 = rotationalPoint[0];
  int y1 = rotationalPoint[1];
  int x2 = point.get()[0];
  int y2 = point.get()[1];

  //skips the point if it's the same as the pivot point
  if(x2 != x1 && y2 != y1){
    //calculate the angle from the pivot point to a given point
    float theta = atan((y2-y1)/(x2-x1));

    println("Theta Before: " + degrees(theta));
    /* These two lines compensate for the fact that atan as a range from PI/2 to -PI/2
    they give the atan function a range from 0 to 2PI
    */
    if(x2-x1 < 0) theta += PI;
    if(x2-x1 > 0 && y2-y1 < 0) theta = 2*PI-abs(theta);

    //some lines to help debug
    println("P1: " + x1 + ", " + y1 + " P2: " + x2 + ", " + y2);
    println("Theta: " + degrees(theta) + " Angle: " + degrees(angle));

    /*checks to see if the current line's angle is close  to the angle from the pivot point to the given point
    if it is then it will make the given point the new pivot point
    */
    if(angle<theta+rotationRate/2 && angle > theta-rotationRate/2){
      this.rotationalPoint[0] = x2;
      this.rotationalPoint[1] = y2;
    }
  }
}
}

Thank you for your help!


Solution

  • The division is taking Integer values as parameters, and because of that, it performs an 'integer division' with no floating point. Parse your values as float before doing the division:

    float ratio = (float)(520-581) / (float)(158-87);
    System.out.println(ratio);
    
    -0.85915494
    

    Good luck!