c++ - 在C++中查找角度的正弦和余弦值

标签 c++ math trigonometry

我是 C++ 新手,编写了一个小程序来找出角度的正弦和余弦值。我的示例代码如下:

#include <math.h>
#include <iostream>
#include <iomanip>
using namespace std;
#define PI 3.14159265

int main ()
{
    double rate, result;
    rate = 90.0;
    result = cos (rate*PI/180);
    cout<<"The cosine of " << rate << " degrees is " << result <<endl;
    return 0;
}

我得到 1.7949e-009 作为 cos(90) 的结果。有没有办法得到 0 作为结果(在结果变量中)而不是这种格式?同样的问题也发生在 180 度的 sin 上。我想要一个结果值为 0 的情况的通用解决方案。

最佳答案

由于您标记了帖子 C++ 而不是 C,所以让我给您一些 C++ 提示:

  1. 数学的标准标题是 <cmath>而不是<math.h>
  2. 在 C++ 中,有更好的方法来声明常量 #define
  3. float 并不是实数的精确表示(实数不存在计算精确表示),因此最终总会出现舍入错误。

获得结果的更惯用的方法是:

#include <cmath>
#include <iostream>
#include <iomanip>

int main ()
{
    const auto PI = std::acos(-1); //let the  computer to find out what PI is

    double rate{}, result{}; //don't let uninitialized values
    rate = 90.0;
    result = std::cos (rate*PI/180);
    std::cout<<"The cosine of " << // set outoput precison for floating point
         std::setprecision(4) << rate << " degrees is " << 
         std::setprecision(4) << result <<endl;
    return 0;
}

注意我是如何让std::显式:C++ <cmath>数学函数的重载比 C 多。

参见:

另请注意,虽然更准确的 PI 使得 result为了更准确,结果总是有可能不完美,因此 - 当显示浮点值时 - 将精度设置为足以补偿换向误差的水平,该水平对您的问题有意义。

实数的表示精度可以从 std::numeric_limits<double>::digits10 得到(来自 <limits> header ):删除 2-3 位数字总是好的。

此外,在进行减法或比较时,请考虑舍入误差:请参阅 std::numeric_limits::epsilon 中的示例引用文档:

#include <cmath>
#include <limits>
#include <iomanip>
#include <iostream>
#include <type_traits>
#include <algorithm>

template<class T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
    almost_equal(T x, T y, int ulp)
{
    // the machine epsilon has to be scaled to the magnitude of the values used
    // and multiplied by the desired precision in ULPs (units in the last place)
    return std::abs(x-y) < std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp
    // unless the result is subnormal
           || std::abs(x-y) < std::numeric_limits<T>::min();
}
int main()
{
    double d1 = 0.2;
    double d2 = 1 / std::sqrt(5) / std::sqrt(5);

    if(d1 == d2)
            std::cout << "d1 == d2\n";
    else
            std::cout << "d1 != d2\n";

    if(almost_equal(d1, d2, 2))
            std::cout << "d1 almost equals d2\n";
    else
            std::cout << "d1 does not almost equal d2\n";
}

这表明 sqrt(5) 的平方不是 ... 5,即使你设法看起来是这样:

(剧透:输出是

d1 != d2
d1 almost equals d2

) ;-)

关于c++ - 在C++中查找角度的正弦和余弦值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40013267/

相关文章:

c++ - 没有除了风格和性能的练习?

c++ - 在运行时旋转俄罗斯方 block

algorithm - MBS 的一维装箱问题算法(最小装箱松弛度)

static-analysis - Code Contracts静态检查器是否应该能够检查算术界限?

c - 我怎样才能将一个数字与其他数字进行比较而不用 C 语言将它们全部写出来?

math - 如何计算等距矩形/正方形的高度和宽度

c++ - int `*p = new int(5);` 和 `int *p = new int[5];` 有什么区别

c++ - sizeof() 函数后跟方括号

math - 在 Sass 中舍入数字并调整小数位数

创建自定义正弦函数