gnuplotnan

gnuplot: How to compare to NaN?


There are several topics here about this (in javascript, c++,...), but haven't yet found one for gnuplot.

Basically, I want to replace "nan" with "---" in labels.

I know that I can set NaN = "---" but then NaN behaves like a string and other code needs to be adapted.

### How to compare to NaN?
NaN = GPVAL_NaN  # default value for NaN

a = NaN
print (a==NaN ? "---" : sprintf("%g",a))
print (a==NaN ? sprintf("%g",a) : "---")
print (a!=NaN ? "---" : sprintf("%g",a))
print (a!=NaN ? sprintf("%g",a) : "---")

a = 123
print (a==NaN ? "---" : sprintf("%g",a))
print (a==NaN ? sprintf("%g",a) : "---")
print (a!=NaN ? "---" : sprintf("%g",a))
print (a!=NaN ? sprintf("%g",a) : "---")
### end of code

The result:

NaN
---
NaN
---
123
---
123
---

So, none of the combination does the job.

Finally, I found that the following seems to work.

print (a/a == 1 ? sprintf("%g",a) : "---")

My questions:

Will a/a always be exactly 1 or could there potentially be rounding errors in special cases? Is this "the" way how to do it or did I overlook anything?


Solution

  • just for the sake of not letting this question appearing unanswered...

    Probably, the easiest way to compare if a variable a is NaN or not (at least in gnuplot) and do something with it:

    print (a == a ? sprintf("%g",a) : "---")
    

    Following some discussions on some programming languages here on SO, people are debating about NaN==NaN or NaN!=NaN or neither of them.

    And in case of comparison to the string "NaN" in data: see @Christoph's comment above.