MPFR
|
A C library for Multiple-Precision Floating-point computations with correct Rounding.
GMP를 사용한 실수전용 라이브러리
예제 ¶다음은 200-bit 정밀도(precision)로 1+1/1!+1/2!+...+1/100!를 구하는 프로그램입니다.
mpfr_t s, t, u;
세개의 s, t, u 실수를 정의
mpfr_init2 (t, 200);
200-bit 정밀도로 초기화
mpfr_set_d (t, 1.0, GMP_RNDD);
변수 t에 double형 변수 1.0을 집어넣되, -Infinity쪽(downward rounding) 반올림을 하도록 한다. (이 경우 반올림이 일어나지 않는데, 1은 200비트에서 정확하게 1로 표현되기 때문.
mpfr_mul_ui (t, t, i, GMP_RNDU);
t에 unsigned int인 i를 곱해서 t에 넣는다. 결과값은 +Infinity쪽 (upward rounding)
mpfr_div (u, u, t, GMP_RNDD);
u를 t로 나눈다. 결과는 -Infinity쪽으로 반올림하고 u에 저장한다.
mpfr_out_str (stdout, 10, 0, s, GMP_RNDD);
10을 base로 하는 출력을 s로 -Infinity쪽으로 반올림. 세번째 인자 0은 프린트될 숫자를 자동으로 설정하도록 한다.
mpfr_clear
MPFR에서 사용된 공간을 지운다.
#include <stdio.h>
#include <gmp.h>
#include <mpfr.h>
int main (void)
{
unsigned int i;
mpfr_t s, t, u;
mpfr_init2 (t, 200);
mpfr_set_d (t, 1.0, GMP_RNDD);
mpfr_init2 (s, 200);
mpfr_set_d (s, 1.0, GMP_RNDD);
mpfr_init2 (u, 200);
for (i = 1; i <= 100; i++)
{
mpfr_mul_ui (t, t, i, GMP_RNDU);
mpfr_set_d (u, 1.0, GMP_RNDD);
mpfr_div (u, u, t, GMP_RNDD);
mpfr_add (s, s, u, GMP_RNDD);
}
printf ("Sum is ");
mpfr_out_str (stdout, 10, 0, s, GMP_RNDD);
putchar ('\n');
mpfr_clear (s);
mpfr_clear (t);
mpfr_clear (u);
return 0;
}
결과
$ ./sample Sum is 2.718281828459045235360287471352662497757247093699959574966913 |
You have an ability to sense and know higher truth. |











