Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionLast revisionBoth sides next revision | ||
floating-point-equality [2017/11/21 10:28] – awf | floating-point-equality [2021/03/05 09:12] – awf | ||
---|---|---|---|
Line 49: | Line 49: | ||
But hang on, you're on a platform which will give you line number here when you get the divby0 right? | But hang on, you're on a platform which will give you line number here when you get the divby0 right? | ||
So the assert is superfluous -- just enable exceptions on divide by zero, underflow, and overflow. | So the assert is superfluous -- just enable exceptions on divide by zero, underflow, and overflow. | ||
+ | |||
+ | And there' | ||
+ | <code C++> | ||
+ | void my_unit_test() { | ||
+ | my_matrix< | ||
+ | TEST_ASSERT_EQ_APPROX(a(0, | ||
+ | TEST_ASSERT_EQ(a(0, | ||
+ | } | ||
+ | </ | ||
+ | You may worry about excess precision on x86, but there' | ||
==== But my case is more subtle than that ==== | ==== But my case is more subtle than that ==== | ||
Line 61: | Line 71: | ||
</ | </ | ||
- | Even here, you can think about what a better value to compare to might be. First note that sin(x)/x works fine for all normalized | + | Even here, you can think about what a better value to compare to might be. First note that sin(x)/x works fine for all floats except zero, so you can avoid a dependency on fabs and a definition of epsilon by just comparing to zero. |
But perhaps the profiler has told you that a big chunk of program time is spent in computing sin() and dividing, and furthermore you know that most times it's called with values near zero. Well then, let's do what we do with any special function that goes slow: chop up the domain and special case. | But perhaps the profiler has told you that a big chunk of program time is spent in computing sin() and dividing, and furthermore you know that most times it's called with values near zero. Well then, let's do what we do with any special function that goes slow: chop up the domain and special case. | ||
Line 77: | Line 87: | ||
} | } | ||
</ | </ | ||
+ | |||
+ | It's a good idea then to write a blog post about the issue, because Toby Sharp might comment (see below) and point out that there is a much better choice: | ||
+ | |||
+ | > "... since we need some kind of test for x=0 anyway, I don't see why we shouldn' | ||
+ | |||
+ | <code C++> | ||
+ | float sinc(float x) { | ||
+ | // Toby's threshold, determined through binary search as the best value for minimizing absolute error | ||
+ | if (std:: | ||
+ | return 1.0f - (x * x) * (1.0f / 6.0f); | ||
+ | else | ||
+ | return std::sin(x) / x; | ||
+ | } | ||
+ | </ | ||
+ | |||
=== And templates? === | === And templates? === | ||
Line 97: | Line 122: | ||
</ | </ | ||
- | ~~DISCUSSION~~ | + | See also |
+ | * https:// | ||
+ | |||
+ | ~~DISCUSSION: closed |