(C++)2.3浮動小数点
前回整数型を知っていたら、今回は浮動小数点を理解してみましょう.(少しずつ進んでいくのが楽しい^^)
浮動小数点:点が移動しています.つまり、
以前の時間にも言っていましたが、
ヤード方向が0なら+,1ならー.
コードで理解しよう
今は理解できないけど、後で使うと理解できるし、理解しないとスキップ~~~!!
以下のコードを理解しましょう.
(任意の数に100を掛けるよりもe 2を加えて可読性を高める方法もある.)
浮動小数点:点が移動しています.つまり、
100 = 1.0 * 100
を表現する方法は尽きない.以前の時間にも言っていましたが、
sizeof()
を使って直接確認した方がいいです.ヤード方向が0なら+,1ならー.
コードで理解しよう
#include <iostream>
#include <limits>
int main()
{
using namespace std;
float f;
double d;
long double ld;
cout << numeric_limits<float>::max() << endl;
cout << numeric_limits<double>::max() << endl;
cout << numeric_limits<long double>::max() << endl;
cout << endl;
cout << numeric_limits<float>::lowest() << endl;
cout << numeric_limits<double>::lowest() << endl;
cout << numeric_limits<long double>::lowest() << endl;
cout << numeric_limits<long double>::min() << endl;
return 0;
}
output : 3.40282e+38
1.79769e+308
1.79769e+308
-3.40282e+38
-1.79769e+308
-1.79769e+308
2.22507e-308
sizeof()
を使って資料型の大きさを知ることができますが、どれだけ表現できるかを正確に知るには#include <limits>
を使うのが望ましいです.前回もやったことがありますが、よく使うので使い方を知っておきましょう!!cout << numeric_limits<long double>::max() << endl;
とは何か知っていますが、min()
とlowest()
の違いは何ですか?どういう意味ですか?情報を調べると、min()
の場合は最小の有限数、lowest()
の場合は最低の有限数となります.これが何を意味するのか分からない...ちょっと伺います.min()
:割引は0ではありませんが、最小の数です.(負数は発生しません.)lowest()
:表現できる最低数.(負の値が表示される場合があります.)今は理解できないけど、後で使うと理解できるし、理解しないとスキップ~~~!!
以下のコードを理解しましょう.
#include <iostream>
#include <limits>
int main()
{
using namespace std;
float f(3.14);
cout << 3.14 << endl;
cout << 31.4e-1 << endl;
cout << 31.4e-2 << endl;
cout << 31.4e1 << endl;
cout << 31.4e2 << endl;
return 0;
}
output : 3.14
3.14
0.314
314
3140
このコードには特に難しいことはありません.ただeについて知りたいだけです.このe = 10
と同じように考えればいいです.eが乗じているなら10が乗じていると思いますよねしたがって、e1
は10^1e-1
は10^−1である.これは困難な概念ではない.(任意の数に100を掛けるよりもe 2を加えて可読性を高める方法もある.)
#include <iostream>
#include <iomanip>
#include <limits>
int main()
{
using namespace std;
double d1(1.0);
double d2(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1);
//cout << std::setprecision(17);
cout << d1 << endl;
cout << d2 << endl;
return 0;
}
output : 1
1
間違いを犯しやすい内容をよく考えなさいC言語でも1.0と0.1を10回加算出力の値と同じにするとしますか?違うの?出力から見ると同じです.だから同じではないかと思って、全然違います.setprecision()
はI/Oオペレータで、浮動小数点数の基本精度を変更できます.()に3を入れると小数点を3位に出力します.出力はどうなりますか?#include <iostream>
#include <iomanip>
#include <limits>
int main()
{
using namespace std;
double d1(1.0);
double d2(0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1);
cout << std::setprecision(17);
cout << d1 << endl;
cout << d2 << endl;
return 0;
}
output : 1
0.99999999999999989
誤差は蓄積され,このような結果を生じる.何でもないと思うかもしれませんが、ゲームや科学で大きなミスを起こすので気をつけましょう.Reference
この問題について((C++)2.3浮動小数点), 我々は、より多くの情報をここで見つけました https://velog.io/@joon10266/C-2.3-부동소수점テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol