Problems with sin, cos, tan and cot
19 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponses (2)
Ameer Hamza
le 4 Nov 2020
Modifié(e) : Ameer Hamza
le 4 Nov 2020
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 commentaires
Stephen23
le 4 Nov 2020
Modifié(e) : Stephen23
le 4 Nov 2020
"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
le 4 Nov 2020
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.
Steven Lord
le 4 Nov 2020
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
0 commentaires
Voir également
Catégories
En savoir plus sur Startup and Shutdown dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!