【问题标题】:What is a big double that I can use to simulate infinity? [duplicate]我可以用什么来模拟无穷大? [复制]
【发布时间】:2020-04-18 19:58:34
【问题描述】:

我想要一个可以模拟无穷大的大双精度数,但又不能大到占用大量内存。所以,最大的 double 可以被大量使用而不会导致我的程序崩溃。

对于上下文:我正在尝试创建一个函数,该函数返回从两个点创建的两条线段之间的交点,如果没有交点,则返回 null(用于更高的方法来确定对象是否在我的平台游戏)。作为数学/代码的一部分,我需要从两点创建一个线函数,当这条线恰好是垂直的时,它需要有一个无限的斜率。这是我目前所拥有的:

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;
}

那么我可以用什么来做那个大双?谢谢!

【问题讨论】:

  • 我的印象是您认为大双打占用更多内存。 Java double 旨在实现为 IEEE 754 64 位二进制浮点数,因此适合 64 位。
  • 哦,哇,这意味着我可以使用任何我想要的尺寸?这很容易,我可以把那些 64 位最大化!谢谢!

标签: java double


【解决方案1】:

使用任一:

Double.POSITIVE_INFINITY
Double.MAX_VALUE

【讨论】:

  • 我可以用 Double.POSITIVE_INFINITY 做数学吗?例如,如果我这样做:
  • x = 100/Double.POSITIVE_INFINITY 它会破坏一切,还是将 x 设置为接近 0 的数字?编辑:我可以测试一下,不需要回答!
  • @DanielHicks 依赖测试来学习语言特性是很危险的。 100/Double.POSITIVE_INFINITY 正好是 0。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多