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에서 Startup and Shutdown에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!