C++: how can I test if a number is power of ten?

前端 未结 9 1263
清歌不尽
清歌不尽 2021-02-18 19:12

I want to test if a number double x is an integer power of 10. I could perhaps use cmath\'s log10 and then test if x == (int) x?

<

9条回答
  •  你的背包
    2021-02-18 19:39

    A lookup table will be by far the fastest and most precise way to do this; only about 600 powers of 10 are representable as doubles. You can use a hash table, or if the table is ordered from smallest to largest, you can rapidly search it with binary chop.

    This has the advantage that you will get a "hit" if and only if your number is exactly the closest possible IEEE double to some power of 10. If this isn't what you want, you need to be more precise about exactly how you would like your solution to handle the fact that many powers of 10 can't be exactly represented as doubles.

    The best way to construct the table is probably to use string -> float conversion; that way hopefully your library authors will already have solved the problem of how to do the conversion in a way that gives the most precise answer possible.

提交回复
热议问题