Rounding error of std::cbrt?

我的梦境 提交于 2019-12-13 09:30:47

问题


I wonder if the following should be reported as a bug in gcc implementation of standard library.

For all unsigned integers i, if we compare int(std::sqrt(i)) to the actual square root of the integer, the conversion always give the good result. If we do the same with std::cbrt it's not the case :

// Problem of rounding of std::cbrt for i from 0 to 100 million
// i, exact cbrt(i), result of int(std::cbrt(i))
2197, 13, 12
17576, 26, 25
24389, 29, 28
140608, 52, 51
185193, 57, 56
195112, 58, 57
226981, 61, 60
1092727, 103, 102
1124864, 104, 103
1442897, 113, 112
1481544, 114, 113
1560896, 116, 115
1685159, 119, 118
1815848, 122, 121
8741816, 206, 205
8869743, 207, 206
8998912, 208, 207
9393931, 211, 210
9938375, 215, 214
11543176, 226, 225
11852352, 228, 227
12487168, 232, 231
12649337, 233, 232
13481272, 238, 237
13651919, 239, 238
14348907, 243, 242
14526784, 244, 243
14706125, 245, 244
69426531, 411, 410
69934528, 412, 411
70957944, 414, 413
71991296, 416, 415
72511713, 417, 416
73560059, 419, 418
74618461, 421, 420
75151448, 422, 421
79507000, 430, 429
88121125, 445, 444
89314623, 447, 446
91733851, 451, 450
92345408, 452, 451
92959677, 453, 452
94818816, 456, 455
99897344, 464, 463 

Do you think that should be reported as a defect ?


回答1:


std::cbrt returns a floating point type (float, double, etc.) but you are converting it to an int. Such conversions truncate rather than round e.g. 0.9999 becomes 0. Although it may seem logical that the cube root of 2197 is an integer, due to the fact that floating point types are stored in binary, it is not always possible to perfectly represent a decimal number, and such inaccuracies are likely to propagate during the calculations that std::cbrt performs. If for example, std::cbrt(2197) == 12.99999 (my compiler doesn't support it so I can't check the real value), then by converting it to an int you are truncating the value to 12.

To correct your code, round the result of std::cbrt(i) before converting it to an int. See this question for an idea of how to do that.



来源:https://stackoverflow.com/questions/14310163/rounding-error-of-stdcbrt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!