2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ゆるゆる数値計算Advent Calendar 2018

Day 2

ネイピア数の実装 [C/C++]

Last updated at Posted at 2018-12-01

#ネイピア数

今回はC99とC++14で動作するネイピア数eを計算するプログラムを作成する。

##関数e1の実装

###元の式

$\displaystyle e = \lim_{t \to 0} \left(1 + t \right )^\frac{1}{t}$

###近似式

$\displaystyle t = \frac{1}{2^{51}}$

$\displaystyle e = \left(1 + t \right )^\frac{1}{t}$

##関数e2の実装

###元の式

$\displaystyle e = \sum_{n \to 0}^{\infty} \left(\frac{1}{n!} \right )$

###近似式

$\displaystyle e = 2+\sum_{n \to 2}^{18} \left(\frac{1}{n!} \right )$

#ソースコード

C99
#include <stdio.h>
#include <stdint.h>
#include <math.h>

typedef uint_fast64_t u64;

//lim t->0 (1+t)^(1/t)
static const double t = 1.0 / ((u64)1 << 51);
double e1() {
	return pow(1.0 + t, 1.0 / t);
}

//sigma n=0~18 (1/n!)
double e2() {
	double e = 2.0;
	u64 n;
	for (u64 i = (u64)2; i < (u64)18; ++i) {
		n = (u64)1;
		for (u64 j = (u64)2; j <= i; ++j) n *= j;
		e += (1.0 / n);
	}
	return e;
}
static const double e = e2();
static const double ee = 2.718281828459045;

int main() {
	printf("%.16f\n", e1());
	printf("%.16f\n", e2());
	printf("%.16f\n", e);
	printf("%.16f\n", ee);
	return 0;
}
C++14
#include <cstdio>
#include <cstdint>
#include <cmath>

namespace math {

	using u64 = uint_fast64_t;

	//lim t->0 (1+t)^(1/t)
	constexpr double t{ 1.0 / ((u64)1 << 51) };
	double e1(const double t_ = t) {
		return std::pow(1.0 + t_, 1.0 / t_);
	}

	//sigma n=0~18 (1/n!)
	constexpr double e2() {
		double e{ 2.0 };
		u64 n{};
		for (u64 i = (u64)2; i < (u64)18; ++i) {
			n = (u64)1;
			for (u64 j = (u64)2; j <= i; ++j) n *= j;
			e += (1.0 / n);
		}
		return e;
	}
	constexpr double e{ e2() };
	constexpr double ee{ 2.718281828459045 };

}

int main() {
	std::printf("%.16f\n", math::e1());
	std::printf("%.16f\n", math::e2());
	std::printf("%.16f\n", math::e);
	std::printf("%.16f\n", math::ee);
	return 0;
}
実行結果
2.7182818284590446
2.7182818284590455
2.7182818284590455
2.7182818284590451

##ソースコードのライセンス

These codes are licensed under CC0.
CC0

ソースコードは自由に使用してください。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?