Problems with sin, cos, tan and cot
古いコメントを表示
why there is a problem with tan, cot, sin and cos of Pi,0, or Pi/2
some of these should give zero but it gives a very small number.
回答 (2 件)
Ameer Hamza
2020 年 11 月 4 日
編集済み: Ameer Hamza
2020 年 11 月 4 日
This is caused by the finite-precision of floating-point datatypes and numerical algorithm to calculate the values of these functions. If you want an exact answer for any input to the trigonometric functions, then you need to use symbolic mathematics.
>> cos(pi/2)
ans =
6.1232e-17
>> cos(sym(pi)/2)
ans =
0
4 件のコメント
Stephen23
2020 年 11 月 4 日
"...you need to use symbolic mathematics"
...with the understanding that this will be much slower than simple numeric operations.
Behnam Bahr
2020 年 11 月 4 日
"But such a software should not be working like this."
Excel:
COS(PI()/2)
6.1257422745431E-17
Haskell:
main = do
print(cos(pi/2))
6.123233995736766e-17
Java:
public class Main {
public static void main(String args[]) {
double x = Math.PI / 2;
System.out.println(Math.cos(x));
}
}
6.123233995736766E-17
Julia:
print(cos(pi/2))
6.123233995736766e-17
Lua:
io.write( math.cos(math.pi / 2) )
6.1232339957368e-17
Octave:
>> cos(pi/2)
ans = 6.123031769111886e-17
Python:
import math
math.cos(math.pi/2)
Out[7]: 6.123233995736766e-17
R:
cos(pi/2)
[1] 6.123234e-17
Ruby:
puts Math.cos(Math::PI/2)
6.123233995736766e-17
Scala:
object HelloWorld {
def main(args: Array[String]) {
println(math.cos(math.Pi/2))
}
}
$scala HelloWorld
6.123233995736766E-17
Scilab:
cos(%pi/2)
ans =
6.123D-17
etc. etc.
"A simple calculator does it much better."
Ameer Hamza
2020 年 11 月 4 日
The numerical errors in using finite-precision are not limited to MATLAB and are fundamental because of the way they are defined. As Stephen already mentioned, symbolic computation will be much slower than floating-point operations. It is a compromise between speed and accuracy. You can try to reduce it, but never completely avoid it.
If you're computing sin, cos, etc. of either angles in degrees or angles that a multiple of pi radians there are other ways to compute than the straightforward sin(x*180/pi) or sin(x*pi).
format
A = 0:45:360
sineInDegrees = sind(A)
isSindOf180Exactly0 = sineInDegrees(5) == 0
sineOfMultiplesOfPi = sinpi(A/180)
isSinpiOfPiExactly0 = sineOfMultiplesOfPi(5) == 0
カテゴリ
ヘルプ センター および File Exchange で Develop Apps Using App Designer についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!