简体   繁体   English

c++ 中的三角函数不会返回正确的值

[英]Trignometry functions in c++ wont return the right values

cout << sinf(M_PI) << ", " << cosf(M_PI/2);

returns -8.74228e-08, -4.37114e-08返回-8.74228e-08, -4.37114e-08

what is the smartest way to approach this problem?解决这个问题最聪明的方法是什么?

I already found out that as the fewer decimal places I round PI to, the closer the functions returns the correct result.我已经发现,随着我将 PI 舍入到的小数位数越少,函数返回的结果就越接近正确。 See here:看这里:

    float pi = 3.14;
    cout << sinf(pi) << ", " << cosf(pi/2);

returns:回报:

0.00159255, 0.000796274

But is there a way to maximize the accuracy without eliminating the decimal places?但是有没有办法在不消除小数位的情况下最大限度地提高准确性呢?

The number 8.74228e-08 is less than a tenth of a millionth;数字 8.74228e-08 小于百万分之一; this is a much smaller number than 0.00159255.这是一个比 0.00159255 小得多的数字。 Single precision floats only give you about 7 significant digits of precision so this is essentially zero as far as a 32-bit float is concerned.单精度浮点数只能为您提供大约 7 位有效数字的精度,因此就 32 位浮点数而言,这基本上为零。

Generally you should not expect floating point numbers to have exact values.通常,您不应期望浮点数具有精确值。 It is not uncommon for floating point numbers to have a small amount of error when compared to the true value of a number to begin with (as some numbers, even with non-repeating decimal expansions, cannot be represented exactly with floating point numbers) and pi obviously can't be represented exactly in decimal form at all.与开始的数字的真实值相比,浮点数有少量误差的情况并不少见(因为有些数字,即使有非重复的十进制扩展,也不能用浮点数精确表示)和pi 显然根本不能以十进制形式精确表示。

If you want to display floating point numbers and not get scientific notation in your output, use std::setprecision .如果要在 output 中显示浮点数而不获取科学记数法,请使用std::setprecision setprecision 。 When working with floating point numbers, never test them for equality against exact values.使用浮点数时,切勿测试它们是否与精确值相等。 Test that the absolute value of their difference from exact values is less than a tolerance, usually referred to as epsilon.测试它们与精确值之差的绝对值是否小于公差,通常称为 epsilon。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM