floating-point-precision

Correct use of std::cout.precision() - not printing trailing zeros

一个人想着一个人 提交于 2019-11-26 06:07:30
问题 I see many questions about the precision number for floating point numbers but specifically I want to know why this code #include <iostream> #include <stdlib.h> int main() { int a = 5; int b = 10; std::cout.precision(4); std::cout << (float)a/(float)b << \"\\n\"; return 0; } shows 0.5 ? I expect to see 0.5000 . Is it because of the original integer data types? 回答1: #include <iostream> #include <stdlib.h> #include <iomanip> int main() { int a = 5; int b = 10; std::cout << std::fixed; std::cout

How to avoid floating point errors?

醉酒当歌 提交于 2019-11-26 05:14:04
I was trying to write a function to approximate square roots (I know there's the math module...I want to do it myself), and I was getting screwed over by the floating point arithmetic. How can you avoid that? def sqrt(num): root = 0.0 while root * root < num: root += 0.01 return root Using this has these results: >>> sqrt(4) 2.0000000000000013 >>> sqrt(9) 3.00999999999998 I realize I could just use round() , but I want to be able to make this really accurate. I want to be able to calculate out to 6 or 7 digits. That wouldn't be possible if I'm rounding. I want to understand how to properly

How to avoid floating point errors?

女生的网名这么多〃 提交于 2019-11-26 01:45:45
问题 I was trying to write a function to approximate square roots (I know there\'s the math module...I want to do it myself), and I was getting screwed over by the floating point arithmetic. How can you avoid that? def sqrt(num): root = 0.0 while root * root < num: root += 0.01 return root Using this has these results: >>> sqrt(4) 2.0000000000000013 >>> sqrt(9) 3.00999999999998 I realize I could just use round() , but I want to be able to make this really accurate. I want to be able to calculate

Printf width specifier to maintain precision of floating-point value

…衆ロ難τιáo~ 提交于 2019-11-26 01:18:55
问题 Is there a printf width specifier which can be applied to a floating point specifier that would automatically format the output to the necessary number of significant digits such that when scanning the string back in, the original floating point value is acquired? For example, suppose I print a float to a precision of 2 decimal places: float foobar = 0.9375; printf(\"%.2f\", foobar); // prints out 0.94 When I scan the output 0.94 , I have no standards-compliant guarantee that I\'ll get the