3.12 부동 소수점의 오류

공기훈·2021년 7월 21일
0

홍정모의 따배씨

목록 보기
2/49

//round-off errors (ex1)

#include <stdio.h>
#include <float.h>
int main()
{
    float a, b;
	a = 1000.0f + 1.0f;
	b = a - 1000.0f;
	printf("%f\n", b); //1.0000 출력
	
    float c, d;
	c = 1.0E20f + 1.0f;
	d = c - 1.0E20f;
	printf("%f\n", d); //0.0000 출력 
	// 너무 큰 숫자에 조그만 수 더해버리면 조그만 수가 사라짐.. 무한대 생각하면 될 듯?
}    

//round-off errors (ex2)

#include <stdio.h>
#include <float.h>
int main()
{
	float a = 0.0f;
	a = a + 0.01f; //이 식을 100번 반복... -> 1.0이 나오는 게 아니라 0.9999가 나옴
	//부동 소수점에서는 0.01을 0.00999..로 나타내짐. 이 오차가 누적되어 백 번 더하면 0.9999가 나오게 됨
	
printf("%f\n", a);
}

//overflow

#include <stdio.h>
#include <float.h>
int main()
{    	
	float max = 3.402823466e+38F; //float가 나타낼 수 있는 가장 큰 수
	printf("%f\n", max); //340282346638528859811704183484516925440.000000

	max = max * 100.0f;
	printf("%f\n", max); //inf = infinite 가 나타남. float가 지닐 수 있는 범위를 넘었기 때문에 이와 같이 뜸.

	double Max = 1.7976931348623158e+308; // double이 나타낼 수 있는 가장 큰 수
	printf("%f\n", Max);
	
	Max = Max * 100.0f;
	printf("%f\n", Max); //inf
}

//underflow

#include <stdio.h>
#include <float.h>
int main()
{
	float f = 1.401298464e-45F;
	printf("%e\n", f); //1.401298e-45

	f = f / 100.0f; //subnormal. 정밀도를 잃게 됨.
	printf("%e\n", f); //0.000000e+00  

	float a = 104.0f;
	printf("%f\n", a); //104.0000
	a = a / 0.0f;
	printf("%f\n", a); //inf
}

수학적 식

<math.h> include

#include <stdio.h>
#include <float.h>
#include <math.h>

int main()
{
	float f = asinf(1.0f); //asin = arcsin
	printf("%f\n", f); //1.570796
	f = asinf(2.0f);
	printf("%f\n", f); //-nan(ind) .. nan(not a number) 
	return 0;
}
profile
be a coding master

0개의 댓글