在C中实现余弦函数

问题描述 投票:0回答:1

我必须实现 C 的

double cos(double x)
库中存在的我自己版本的
<math.h>
函数。

这个功能的实现有些地方不太明白。

原则上,我必须

接收用户输入(例如,

double x
),在该
double x
上实现余弦的泰勒级数。并返回一个双数。

我需要将我的实现与内置的

double cos(double x)
进行比较,并将其打印出来。

我的函数需要精确到1.0e-6的级别(即百万分之一,数字后7位小数)

我似乎对这种实现缺乏基本的理解,因为我在这里偶然发现了很多问题。


我的用户输入不正确。我应用了两个数字,它不仅打印出错误的数字,而且每次都打印出随机数字。

我使用余弦泰勒级数计算余弦值的方式也可能是不正确的。

内置

double cos(double x)
函数具有相同的行为,每次都会打印错误的数字随机数字。


我使用了GCC编译器,并使用以下行编译了文件:

gcc -ansi -Wall -pedantic my_cos.c -lm

正如你所知,这些结果的一切都是……错误的:


这是我的 my_cos.h 文件:

#define PI 3.1415926535
    
double my_cos(double);

这是我的 my_cos.c 文件:

#include <stdio.h>
#include <math.h>
#include "my_cos.h"


double my_cos(double x)
{
  double cos = 1 - ((pow(x,2))/(2)) + ((pow(x,4))/(24)) - ((pow(x,6))/(1*2*3*4*5*6)) + ((pow(x,8))/(1*2*3*4*5*6*7*8)) - ((pow(x,10))/(1*2*3*4*5*6*7*8*9*10));
  return cos * ((PI)/(180)); 
}

int main()
{
  double x;
  printf("Please insert a number:");
  scanf("%f", &x);

  printf("Your number is: %f\n", x);

  printf("using my function:");
  printf("%.7f\n", my_cos(x));

  printf("Using C's function:");
  printf("%f\n", cos(x));
   
  return 0;
}

这条长线

double cos = 1 - ((pow(x,2))/(2)) + ((pow(x,4))/(24)) - ((pow(x,6))/(1*2*3*4*5*6)) + ((pow(x,8))/(1*2*3*4*5*6*7*8)) - ((pow(x,10))/(1*2*3*4*5*6*7*8*9*10));

是余弦泰勒级数的实现:

这行

return cos * ((PI)/(180));
应该是从度数形式到弧度形式的转换,因为内置函数还返回以弧度为单位的参数的余弦值。

我非常希望获得有关如何解决这些问题和改进我的程序的建议。

c trigonometry math.h
1个回答
0
投票

您必须将余弦的参数转换为弧度,而不是结果。只要您

return cos;
,您的日常工作就可以正常进行。那么它与
cos()
功能非常匹配。

© www.soinside.com 2019 - 2024. All rights reserved.