0

I want a big double that can simulate infinity, but not so big that it takes up a lot of memory. So, the biggest double possible that can be used a lot without crashing my program.

For context: I am trying to make a function that returns the point of intersection between two line segments created from two points each, or null if there is no intersection (used in a higher up method to determine if objects are colliding in my plat-former game). As part of the math/code, I need to create a line function from the two points, and when that line happens to be vertical it needs to have an infinite slope. Here is what I have so far:

public static Point intersect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
    //calcs slopes
    double m1 = bigDouble; //infinity!
    if (x1==x2) m1 = (y2-y1) / (x2-x1); //if its not vertical, calc the slope
    double m2 = bigDouble;
    if (x3==x4) m2 = (y4-y3) / (x4-x3);
    //calcs b in y=mx+b
    int b1 = (int) (m1*x1+y1);
    int b2 = (int) (m2*x3+y3);
    //checks that lines are not parallel
    if (m1==m2) return null;
    //calcs intersection
    int x = (int) ((b2-b1)/(m1-m2));
    int y = (int) (m1*x+b1);
    //checks that intersection is within bounds of segments
    if (isOutside(x,x1,x2)||isOutside(y,y1,y2)||isOutside(x,x3,x4)||isOutside(y,y3,y4)) return null;
    //returns intersection point
    return new Point(x,y);
}

public static boolean isOutside (int num, int bound1, int bound2) {
    return num<getMin(bound1,bound2) || num>getMax(bound1, bound2);
}

public static int getMin(int num1, int num2) {
    if (num1>num2) return num2;
    return num1;
}

public static int getMax(int num1, int num2) {
    if (num1>num2) return num1;
    return num2;
}

So what can I use for that big double? Thanks!

  • I get the impression that you think large doubles take more memory. Java double is designed to be implemented as IEEE 754 64-bit binary floating point, and therefore fits in 64 bits. – Patricia Shanahan Dec 30 '19 at 03:07
  • Oh wow, so that means I can use any size I want? Thats easy, I can just max out those 64 bits then! Thanks! –  Dec 30 '19 at 03:49

1 Answers1

2

Use either:

Double.POSITIVE_INFINITY
Double.MAX_VALUE
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Can I do math with Double.POSITIVE_INFINITY ? For example, if I do: –  Dec 30 '19 at 03:51
  • x = 100/Double.POSITIVE_INFINITY will it break everything, or set x to a number close to 0? Edit: I can just test that, no need to answer! –  Dec 30 '19 at 03:51
  • @DanielHicks It can be dangerous to depend on tests to learn language features. 100/Double.POSITIVE_INFINITY is exactly 0. – Patricia Shanahan Dec 30 '19 at 08:06