What is better for testing for non-final IsNaN or IsInf floats?

I need to check non-final floats and eliminate them. I planned to use math.IsInf() to test floats, but I saw some ppl using math.IsNaN() for this purpose. Is one of them better for this purpose than the other? and if so, why?

edit: This was suspended because it is unclear, so here is more information that hopefully clarifies the issue. I performed Exercise 3.1 from the “Go Programming Language”, which refers to this program . This exercise sets

If the f function returns a non-finite float64 value, the SVG file will contain invalid elements (although many SVG handlers handle> this elegantly). Modify the program to skip invalid polygons.

I planned to solve this problem by adding the following to the corner function

 if math.IsInf(z, 0) { return math.NaN(), math.NaN() } 

and changing the contents of the second for the loop in main to

 ax, ay := corner(i+1, j) if math.IsNaN(ax) { continue } bx, by := corner(i, j) if math.IsNaN(bx) { continue } cx, cy := corner(i, j+1) if math.IsNaN(cx) { continue } dx, dy := corner(i+1, j+1) if math.IsNaN(dx) { continue } fmt.Printf("<polygon points='%g,%g %g,%g %g,%g %g,%g'/>\n", ax, ay, bx, by, cx, cy, dx, dy) 

I wanted to check my work, so I decided to find any answers that other ppl posted on the Internet on this issue. None of those I found used math.IsInf() there, but most of them used math.IsNaN() . This made me wonder if I was missing something, and if for some reason it is better for this purpose. So I looked at Go Docs for both functions. I looked at NaN on Wikipedia and IEEE 754. I did a general search on the Internet why everyone else used math.IsNaN() , although it seemed less intuitive to me. Then I did a search here and on stackoverflow for answers after all that I really had no answer, so I decided to post the question.

+7
go nan
source share
2 answers

If you only need to consider infinity, then math.IsInf() should be enough. However, if you need to protect yourself from infinity and values ​​that are not numbers, you should use them together.

More on floats: https://en.wikipedia.org/wiki/IEEE_754

The math.IsNaN() example does not work for infinite values: https://play.golang.org/p/blHjr8i7p9

+4
source share

Mathematically speaking, it is strange that NaN is a thing in programming, because invalid expressions should not be compiled (unfortunately, they are all the same).

Use math.IsNaN() if your number is not suitable for a real string (e.g. sqrt (-1)) or if it is mathematically undefined (e.g. 0/0).

Use math.IsInf() if your number can be really large (in positive or negative direction), so that you don't have enough bits to represent it, or if it really should be infinite.

-2
source share

All Articles