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

哪个更适合测试非有限浮点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条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码