doutui8842 2017-09-18 16:38
浏览 47
已采纳

哪个更适合测试非有限浮点IsNaN或IsInf?

I need to test for non finite floats and eliminate them. I was planing to use math.IsInf() to test the floats but I have seen some ppl using math.IsNaN() for this purpose. Is one of these better for this purpose than the other ? and if so why?

edit: This has been put on hold because it is unclear so here is more information that will hopefully clarify the question. I was doing exercise 3.1 from "The Go Programming Language" which references this program. The exercise it asks

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

I was planing to solve it by adding the following to the corner func

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

and changing the contents of the second for 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'/>
",
           ax, ay, bx, by, cx, cy, dx, dy)

I wanted to check my work so I decided to look up any answers other ppl had posted online to this problem. No one else that I found had used math.IsInf() in there solutions but most had used math.IsNaN() . This made me wonder if I was missing some something and if math.IsNaN() was better for this purpose for some reason. So I looked through the Go Docs for both functions. I looked up NaN on wikipedia and the IEEE 754. I did general web searches for why everyone else was using math.IsNaN() even though it seemed less intuitive to me. Then I did searches on here and on stackoverflow for answers after all of that I didn't really have an answer so I decided to post a question.

  • 写回答

2条回答 默认 最新

  • dongmei8460 2017-09-18 20:34
    关注

    If you only need to account for either infinities, then math.IsInf() should suffice. However, if you need to guard against both infinities and values that are not numbers, you should use both in conjunction.

    For more reading on floats: https://en.wikipedia.org/wiki/IEEE_754

    An example of math.IsNaN() not working for infinite values: https://play.golang.org/p/blHjr8i7p9

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?