用泰勒公式实现Sin(x)函数的值计算

直接上代码

#include <iostream>
#include <cmath>//Math库用于对比运算结果

using namespace std;

double MySin(double x, double r);

int main(void)
{
	double x;

	cout.precision(12);
	cout << "输入一个数,求其正弦(将显示12个有效数字):";
	cin >> x;
	cout << "Ansters(精度 3位) = " << MySin(x, 1e-3) << endl;
	cout << "Ansters(精度 4位) = " << MySin(x, 1e-4) << endl;
	cout << "Ansters(精度 5位) = " << MySin(x, 1e-5) << endl;
	cout << "Ansters(精度 6位) = " << MySin(x, 1e-6) << endl;
	cout << "Ansters(精度 7位) = " << MySin(x, 1e-7) << endl;
	cout << "Ansters(使用库)   = " << sin(x) << endl;//只是对比验证用
	system("pause");
	return 0;
}

double Exponentiation(double x, int y);
int factorial(int i);

double MySin(double x, double r)//自定义求正弦的函数,r误差
{
	double ans = 0, i = 0;
	int n = 1, s = -1;
	do {
		ans += (s == 1 ? s = -1 : s = 1) * (i = (Exponentiation(x, n) / factorial(n)));
		n += 2;
	} while (r < i);
	return ans;
}

double Exponentiation(double x, int y)//计算x的y(整数)次幂
{
	double ans = 1;
	if (y == 0)
		return 1;
	while (y >= 1)
	{
		ans *= x;
		y--;
	}
	return ans;
}

int factorial(int i)//计算正整数的阶乘,递归方法
{
	if (i >= 1)
		return i * factorial(i - 1);
	else
		return 1;
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值