map(NaN) which returns NaN 但我无法调试 NaN

map(NaN) which returns NaN but I cannot debug for NaN

我提供了一个片段来说明我的问题。 基本上处理给我这个错误:

map(NaN, -3, 3, -125, 125) called, which returns NaN (not a number)

我理解此消息的方式是映射函数 returns NaN,并且由于它 returns 一个浮点数,我应该能够使用 Float.NaN 进行检查。正如所证明的那样,虽然我在创建检查它的 if 语句时没有得到一次命中。我试图将 if 语句放在带有相应变量的 map 函数之前,但没有命中。我想知道是否有人可以向我解释这种现象并帮助我调试代码。这可能是我正在监督的一些小事,但它让我抓狂。提前致谢

片段:

void setup() {
  size(500, 500);
}

void draw() {
  background(0);
}

class Complex {
  private float re, im, r, p;

  Complex(float real, float imag) {
    re = real;
    im = imag;
    r = sqrt(sq(re)+sq(im)); //radius 
    p = atan2(im, re);       //phase
  }

  Complex Div(Complex b) {
    Complex a = this;
    float real = (a.re*b.re+a.im*b.im)/(sq(b.re)+sq(b.im));
    float imag = (a.im*b.re-a.re*b.im)/(sq(b.re)+sq(b.im));
    return new Complex(real, imag);
  }

  Complex Ln() {
    float real = log(r);
    float imag = p;
    return new Complex(real, imag);
  }

  Complex LogBase(Complex b) {
    Complex a = this;
    return a.Ln().Div(b.Ln());
  }

  Complex Scale(float scale, int dim) {
    float real = map(re, -scale, scale, -dim, dim);
    float imag = map(im, -scale, scale, -dim, dim);
    if (real == Float.NaN || imag == Float.NaN) {
      print("\nHit!");
    }
    return new Complex(real, imag);
  }
}

void keyPressed() {
  float d = width/4;
  for (float z = -d; z<d; z++) {
    for (float x = -d; x<d; x++) {
      Complex c = new Complex(1, 5);
      c = c.LogBase(new Complex(x, z));
      c.Scale(3.0, int(d));
    }
  }
}

看起来误解是围绕着与 NaN 的比较。任何与 NaN 的等价比较 (==) 都将 return 为假。即便是和自己比,也是如此。要检查 NaN 值,您可以使用 Float.isNaN 方法。

例如

    System.out.println("(Float.NaN == Float.NaN) -> " + (Float.NaN == Float.NaN));
    System.out.println("(Float.isNaN(Float.NaN)) -> " + (Float.isNaN(Float.NaN)));

产生:

(Float.NaN == Float.NaN) -> false
(Float.isNaN(Float.NaN)) -> true