Trigonometric functions: Difference between revisions
m →{{header|REXX}}: changed comments, added whitespace. -- ~~~~ |
|||
Line 1,011: | Line 1,011: | ||
' ( or, 0.785398163397448 radians ) |
' ( or, 0.785398163397448 radians ) |
||
'----------------------- End of Liberty Basic Section ------------- |
|||
end function</lang> |
|||
Revision as of 20:26, 16 August 2012
You are encouraged to solve this task according to the task description, using any language you may know.
If your language has a library or built-in functions for trigonometry, show examples of sine, cosine, tangent, and their inverses using the same angle in radians and degrees. For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle). For the inverse functions, use the same number and convert its answer to radians and degrees. If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
ACL2
(This doesn't have the inverse functions; the Taylor series for those take too long to converge.)
<lang Lisp>(defun fac (n)
(if (zp n) 1 (* n (fac (1- n)))))
(defconst *pi-approx*
(/ 3141592653589793238462643383279 (expt 10 30)))
(include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)
(defun dgt-to-str (d)
(case d (1 "1") (2 "2") (3 "3") (4 "4") (5 "5") (6 "6") (7 "7") (8 "8") (9 "9") (0 "0")))
(defmacro cat (&rest args)
`(concatenate 'string ,@args))
(defun num-to-str-r (n)
(if (zp n) "" (cat (num-to-str-r (floor n 10)) (dgt-to-str (mod n 10)))))
(defun num-to-str (n)
(cond ((= n 0) "0") ((< n 0) (cat "-" (num-to-str-r (- n)))) (t (num-to-str-r n))))
(defun pad-with-zeros (places str lngth)
(declare (xargs :measure (nfix (- places lngth)))) (if (zp (- places lngth)) str (pad-with-zeros places (cat "0" str) (1+ lngth))))
(defun as-decimal-str (r places)
(let ((before (floor r 1)) (after (floor (* (expt 10 places) (mod r 1)) 1))) (cat (num-to-str before) "." (let ((afterstr (num-to-str after))) (pad-with-zeros places afterstr (length afterstr))))))
(defun taylor-sine (theta terms term)
(declare (xargs :measure (nfix (- terms term)))) (if (zp (- terms term)) 0 (+ (/ (*(expt -1 term) (expt theta (1+ (* 2 term)))) (fac (1+ (* 2 term)))) (taylor-sine theta terms (1+ term)))))
(defun sine (theta)
(taylor-sine (mod theta (* 2 *pi-approx*)) 20 0)) ; About 30 places of accuracy
(defun cosine (theta)
(sine (+ theta (/ *pi-approx* 2))))
(defun tangent (theta)
(/ (sine theta) (cosine theta)))
(defun rad->deg (rad)
(* 180 (/ rad *pi-approx*)))
(defun deg->rad (deg)
(* *pi-approx* (/ deg 180)))
(defun trig-demo ()
(progn$ (cw "sine of pi / 4 radians: ") (cw (as-decimal-str (sine (/ *pi-approx* 4)) 20)) (cw "~%sine of 45 degrees: ") (cw (as-decimal-str (sine (deg->rad 45)) 20)) (cw "~%cosine of pi / 4 radians: ") (cw (as-decimal-str (cosine (/ *pi-approx* 4)) 20)) (cw "~%tangent of pi / 4 radians: ") (cw (as-decimal-str (tangent (/ *pi-approx* 4)) 20)) (cw "~%")))</lang>
sine of pi / 4 radians: 0.70710678118654752440 sine of 45 degrees: 0.70710678118654752440 cosine of pi / 4 radians: 0.70710678118654752440 tangent of pi / 4 radians: 0.99999999999999999999
ActionScript
Actionscript supports basic trigonometric and inverse trigonometric functions via the Math class, including the atan2 function, but not the hyperbolic functions. <lang ActionScript>trace("Radians:"); trace("sin(Pi/4) = ", Math.sin(Math.PI/4)); trace("cos(Pi/4) = ", Math.cos(Math.PI/4)); trace("tan(Pi/4) = ", Math.tan(Math.PI/4)); trace("arcsin(0.5) = ", Math.asin(0.5)); trace("arccos(0.5) = ", Math.acos(0.5)); trace("arctan(0.5) = ", Math.atan(0.5)); trace("arctan2(-1,-2) = ", Math.atan2(-1,-2)); trace("\nDegrees") trace("sin(45) = ", Math.sin(45 * Math.PI/180)); trace("cos(45) = ", Math.cos(45 * Math.PI/180)); trace("tan(45) = ", Math.tan(45 * Math.PI/180)); trace("arcsin(0.5) = ", Math.asin(0.5)*180/Math.PI); trace("arccos(0.5) = ", Math.acos(0.5)*180/Math.PI); trace("arctan(0.5) = ", Math.atan(0.5)*180/Math.PI); trace("arctan2(-1,-2) = ", Math.atan2(-1,-2)*180/Math.PI); </lang>
Ada
Ada provides library trig functions which default to radians along with corresponding library functions for which the cycle can be specified. The examples below specify the cycle for degrees and for radians. The output of the inverse trig functions is in units of the specified cycle (degrees or radians). <lang ada>with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; with Ada.Float_Text_Io; use Ada.Float_Text_Io; with Ada.Text_IO; use Ada.Text_IO;
procedure Trig is
Degrees_Cycle : constant Float := 360.0; Radians_Cycle : constant Float := 2.0 * Ada.Numerics.Pi; Angle_Degrees : constant Float := 45.0; Angle_Radians : constant Float := Ada.Numerics.Pi / 4.0; procedure Put (V1, V2 : Float) is begin Put (V1, Aft => 5, Exp => 0); Put (" "); Put (V2, Aft => 5, Exp => 0); New_Line; end Put;
begin
Put (Sin (Angle_Degrees, Degrees_Cycle), Sin (Angle_Radians, Radians_Cycle)); Put (Cos (Angle_Degrees, Degrees_Cycle), Cos (Angle_Radians, Radians_Cycle)); Put (Tan (Angle_Degrees, Degrees_Cycle), Tan (Angle_Radians, Radians_Cycle)); Put (Cot (Angle_Degrees, Degrees_Cycle), Cot (Angle_Radians, Radians_Cycle)); Put (ArcSin (Sin (Angle_Degrees, Degrees_Cycle), Degrees_Cycle), ArcSin (Sin (Angle_Radians, Radians_Cycle), Radians_Cycle)); Put (Arccos (Cos (Angle_Degrees, Degrees_Cycle), Degrees_Cycle), Arccos (Cos (Angle_Radians, Radians_Cycle), Radians_Cycle)); Put (Arctan (Y => Tan (Angle_Degrees, Degrees_Cycle)), Arctan (Y => Tan (Angle_Radians, Radians_Cycle))); Put (Arccot (X => Cot (Angle_Degrees, Degrees_Cycle)), Arccot (X => Cot (Angle_Degrees, Degrees_Cycle)));
end Trig;</lang>
Output:
0.70711 0.70711 0.70711 0.70711 1.00000 1.00000 1.00000 1.00000 45.00000 0.78540 45.00000 0.78540 45.00000 0.78540 45.00000 0.78540
ALGOL 68
<lang algol68>main:(
REAL pi = 4 * arc tan(1); # Pi / 4 is 45 degrees. All answers should be the same. # REAL radians = pi / 4; REAL degrees = 45.0; REAL temp; # sine # print((sin(radians), " ", sin(degrees * pi / 180), new line)); # cosine # print((cos(radians), " ", cos(degrees * pi / 180), new line)); # tangent # print((tan(radians), " ", tan(degrees * pi / 180), new line)); # arcsine # temp := arc sin(sin(radians)); print((temp, " ", temp * 180 / pi, new line)); # arccosine # temp := arc cos(cos(radians)); print((temp, " ", temp * 180 / pi, new line)); # arctangent # temp := arc tan(tan(radians)); print((temp, " ", temp * 180 / pi, new line))
)</lang> Output:
+.707106781186548e +0 +.707106781186548e +0 +.707106781186548e +0 +.707106781186548e +0 +.100000000000000e +1 +.100000000000000e +1 +.785398163397448e +0 +.450000000000000e +2 +.785398163397448e +0 +.450000000000000e +2 +.785398163397448e +0 +.450000000000000e +2
AutoHotkey
<lang AutoHotkey>pi := 4 * atan(1)
radians := pi / 4 degrees := 45.0 result .= "`n" . sin(radians) . " " . sin(degrees * pi / 180) result .= "`n" . cos(radians) . " " . cos(degrees * pi / 180) result .= "`n" . tan(radians) . " " . tan(degrees * pi / 180)
temp := asin(sin(radians)) result .= "`n" . temp . " " . temp * 180 / pi
temp := acos(cos(radians)) result .= "`n" . temp . " " . temp * 180 / pi
temp := atan(tan(radians)) result .= "`n" . temp . " " . temp * 180 / pi
msgbox % result /* output
trig.ahk
0.707107 0.707107 0.707107 0.707107 1.000000 1.000000 0.785398 45.000000 0.785398 45.000000 0.785398 45.000000
- /</lang>
AWK
Awk only provides sin(), cos() and atan2(), the three bare necessities for trigonometry. They all use radians. To calculate the other functions, we use these three trigonometric identities:
tangent | arcsine | arccosine |
---|---|---|
With the magic of atan2(), arcsine of y is just atan2(y, sqrt(1 - y * y)), and arccosine of x is just atan2(sqrt(1 - x * x), x). This magic handles the angles arcsin(-1), arcsin 1 and arccos 0 that have no tangent. This magic also picks the angle in the correct range, so arccos(-1/2) is 2*pi/3 and not some wrong answer like -pi/3 (though tan(2*pi/3) = tan(-pi/3) = -sqrt(3).)
atan2(y, x) actually computes the angle of the point (x, y), in the range [-pi, pi]. When x > 0, this angle is the principle arctangent of y/x, in the range (-pi/2, pi/2). The calculations for arcsine and arccosine use points on the unit circle at x2 + y2 = 1. To calculate arcsine in the range [-pi/2, pi/2], we take the angle of points on the half-circle x = sqrt(1 - y2). To calculate arccosine in the range [0, pi], we take the angle of points on the half-circle y = sqrt(1 - x2).
<lang awk># tan(x) = tangent of x function tan(x) { return sin(x) / cos(x) }
- asin(y) = arcsine of y, domain [-1, 1], range [-pi/2, pi/2]
function asin(y) { return atan2(y, sqrt(1 - y * y)) }
- acos(x) = arccosine of x, domain [-1, 1], range [0, pi]
function acos(x) { return atan2(sqrt(1 - x * x), x) }
- atan(y) = arctangent of y, range (-pi/2, pi/2)
function atan(y) { return atan2(y, 1) }
BEGIN { pi = atan2(0, -1) degrees = pi / 180
print "Using radians:" print " sin(-pi / 6) =", sin(-pi / 6) print " cos(3 * pi / 4) =", cos(3 * pi / 4) print " tan(pi / 3) =", tan(pi / 3) print " asin(-1 / 2) =", asin(-1 / 2) print " acos(-sqrt(2) / 2) =", acos(-sqrt(2) / 2) print " atan(sqrt(3)) =", atan(sqrt(3))
print "Using degrees:" print " sin(-30) =", sin(-30 * degrees) print " cos(135) =", cos(135 * degrees) print " tan(60) =", tan(60 * degrees) print " asin(-1 / 2) =", asin(-1 / 2) / degrees print " acos(-sqrt(2) / 2) =", acos(-sqrt(2) / 2) / degrees print " atan(sqrt(3)) =", atan(sqrt(3)) / degrees }</lang>
Output:
Using radians: sin(-pi / 6) = -0.5 cos(3 * pi / 4) = -0.707107 tan(pi / 3) = 1.73205 asin(-1 / 2) = -0.523599 acos(-sqrt(2) / 2) = 2.35619 atan(sqrt(3)) = 1.0472 Using degrees: sin(-30) = -0.5 cos(135) = -0.707107 tan(60) = 1.73205 asin(-1 / 2) = -30 acos(-sqrt(2) / 2) = 135 atan(sqrt(3)) = 60
BASIC
QuickBasic 4.5 does not have arcsin and arccos built in. They are defined by identities found here. <lang qbasic>pi = 3.141592653589793# radians = pi / 4 'a.k.a. 45 degrees degrees = 45 * pi / 180 'convert 45 degrees to radians once PRINT SIN(radians) + " " + SIN(degrees) 'sine PRINT COS(radians) + " " + COS(degrees) 'cosine PRINT TAN(radians) + " " + TAN (degrees) 'tangent 'arcsin thesin = SIN(radians) arcsin = ATN(thesin / SQR(1 - thesin ^ 2)) PRINT arcsin + " " + arcsin * 180 / pi 'arccos thecos = COS(radians) arccos = 2 * ATN(SQR(1 - thecos ^ 2) / (1 + thecos)) PRINT arccos + " " + arccos * 180 / pi PRINT ATN(TAN(radians)) + " " + ATN(TAN(radians)) * 180 / pi 'arctan</lang>
BBC BASIC
<lang bbcbasic> @% = &90F : REM set column width
angle_radians = PI/5 angle_degrees = 36 PRINT SIN(angle_radians), SIN(RAD(angle_degrees)) PRINT COS(angle_radians), COS(RAD(angle_degrees)) PRINT TAN(angle_radians), TAN(RAD(angle_degrees)) number = 0.6 PRINT ASN(number), DEG(ASN(number)) PRINT ACS(number), DEG(ACS(number)) PRINT ATN(number), DEG(ATN(number))</lang>
bc
<lang bc>/* t(x) = tangent of x */ define t(x) { return s(x) / c(x) }
/* y(y) = arcsine of y, domain [-1, 1], range [-pi/2, pi/2] */ define y(y) { /* Handle angles with no tangent. */ if (y == -1) return -2 * a(1) /* -pi/2 */ if (y == 1) return 2 * a(1) /* pi/2 */
/* Tangent of angle is y / x, where x^2 + y^2 = 1. */ return a(y / sqrt(1 - y * y)) }
/* x(x) = arccosine of x, domain [-1, 1], range [0, pi] */ define x(x) { auto a
/* Handle angle with no tangent. */ if (x == 0) return 2 * a(1) /* pi/2 */
/* Tangent of angle is y / x, where x^2 + y^2 = 1. */ a = a(sqrt(1 - x * x) / x) if (a < 0) { return a + 4 * a(1) /* add pi */ } else { return a } }
scale = 50
p = 4 * a(1) /* pi */
d = p / 180 /* one degree in radians */
"Using radians: " " sin(-pi / 6) = "; s(-p / 6) " cos(3 * pi / 4) = "; c(3 * p / 4) " tan(pi / 3) = "; t(p / 3) " asin(-1 / 2) = "; y(-1 / 2) " acos(-sqrt(2) / 2) = "; x(-sqrt(2) / 2) " atan(sqrt(3)) = "; a(sqrt(3))
"Using degrees: " " sin(-30) = "; s(-30 * d) " cos(135) = "; c(135 * d) " tan(60) = "; t(60 * d) " asin(-1 / 2) = "; y(-1 / 2) / d " acos(-sqrt(2) / 2) = "; x(-sqrt(2) / 2) / d " atan(sqrt(3)) = "; a(sqrt(3)) / d
quit</lang>
Output:
Using radians: sin(-pi / 6) = -.49999999999999999999999999999999999999999999999999 cos(3 * pi / 4) = -.70710678118654752440084436210484903928483593768845 tan(pi / 3) = 1.73205080756887729352744634150587236694280525381032 asin(-1 / 2) = -.52359877559829887307710723054658381403286156656251 acos(-sqrt(2) / 2) = 2.35619449019234492884698253745962716314787704953131 atan(sqrt(3)) = 1.04719755119659774615421446109316762806572313312503 Using degrees: sin(-30) = -.49999999999999999999999999999999999999999999999981 cos(135) = -.70710678118654752440084436210484903928483593768778 tan(60) = 1.73205080756887729352744634150587236694280525380865 asin(-1 / 2) = -30.00000000000000000000000000000000000000000000001203 acos(-sqrt(2) / 2) = 135.00000000000000000000000000000000000000000000005500 atan(sqrt(3)) = 60.00000000000000000000000000000000000000000000002463
C
<lang c>#include <math.h>
- include <stdio.h>
int main() {
double pi = 4 * atan(1); /*Pi / 4 is 45 degrees. All answers should be the same.*/ double radians = pi / 4; double degrees = 45.0; double temp; /*sine*/ printf("%f %f\n", sin(radians), sin(degrees * pi / 180)); /*cosine*/ printf("%f %f\n", cos(radians), cos(degrees * pi / 180)); /*tangent*/ printf("%f %f\n", tan(radians), tan(degrees * pi / 180)); /*arcsine*/ temp = asin(sin(radians)); printf("%f %f\n", temp, temp * 180 / pi); /*arccosine*/ temp = acos(cos(radians)); printf("%f %f\n", temp, temp * 180 / pi); /*arctangent*/ temp = atan(tan(radians)); printf("%f %f\n", temp, temp * 180 / pi);
return 0;
}</lang>
Output:
0.707107 0.707107 0.707107 0.707107 1.000000 1.000000 0.785398 45.000000 0.785398 45.000000 0.785398 45.000000
C++
<lang cpp>#include <iostream>
- include <cmath>
- ifdef M_PI // defined by all POSIX systems and some non-POSIX ones
double const pi = M_PI;
- else
double const pi = 4*std::atan(1);
- endif
double const degree = pi/180;
int main() {
std::cout << "=== radians ===\n"; std::cout << "sin(pi/3) = " << std::sin(pi/3) << "\n"; std::cout << "cos(pi/3) = " << std::cos(pi/3) << "\n"; std::cout << "tan(pi/3) = " << std::tan(pi/3) << "\n"; std::cout << "arcsin(1/2) = " << std::asin(0.5) << "\n"; std::cout << "arccos(1/2) = " << std::acos(0.5) << "\n"; std::cout << "arctan(1/2) = " << std::atan(0.5) << "\n";
std::cout << "\n=== degrees ===\n"; std::cout << "sin(60°) = " << std::sin(60*degree) << "\n"; std::cout << "cos(60°) = " << std::cos(60*degree) << "\n"; std::cout << "tan(60°) = " << std::tan(60*degree) << "\n"; std::cout << "arcsin(1/2) = " << std::asin(0.5)/degree << "°\n"; std::cout << "arccos(1/2) = " << std::acos(0.5)/degree << "°\n"; std::cout << "arctan(1/2) = " << std::atan(0.5)/degree << "°\n";
return 0;
}</lang>
C#
<lang csharp>using System;
namespace RosettaCode {
class Program { static void Main(string[] args) { Console.WriteLine("=== radians ==="); Console.WriteLine("sin (pi/3) = {0}", Math.Sin(Math.PI / 3)); Console.WriteLine("cos (pi/3) = {0}", Math.Cos(Math.PI / 3)); Console.WriteLine("tan (pi/3) = {0}", Math.Tan(Math.PI / 3)); Console.WriteLine("arcsin (1/2) = {0}", Math.Asin(0.5)); Console.WriteLine("arccos (1/2) = {0}", Math.Acos(0.5)); Console.WriteLine("arctan (1/2) = {0}", Math.Atan(0.5)); Console.WriteLine(""); Console.WriteLine("=== degrees ==="); Console.WriteLine("sin (60) = {0}", Math.Sin(60 * Math.PI / 180)); Console.WriteLine("cos (60) = {0}", Math.Cos(60 * Math.PI / 180)); Console.WriteLine("tan (60) = {0}", Math.Tan(60 * Math.PI / 180)); Console.WriteLine("arcsin (1/2) = {0}", Math.Asin(0.5) * 180/ Math.PI); Console.WriteLine("arccos (1/2) = {0}", Math.Acos(0.5) * 180 / Math.PI); Console.WriteLine("arctan (1/2) = {0}", Math.Atan(0.5) * 180 / Math.PI);
Console.ReadLine(); } }
}</lang>
Clojure
<lang lisp>(ns user
(:require [clojure.contrib.generic.math-functions :as generic]))
- (def pi Math/PI)
(def pi (* 4 (atan 1))) (def dtor (/ pi 180)) (def rtod (/ 180 pi)) (def radians (/ pi 4)) (def degrees 45)
(println (str (sin radians) " " (sin (* degrees dtor)))) (println (str (cos radians) " " (cos (* degrees dtor)))) (println (str (tan radians) " " (tan (* degrees dtor)))) (println (str (asin (sin radians) ) " " (* (asin (sin (* degrees dtor))) rtod))) (println (str (acos (cos radians) ) " " (* (acos (cos (* degrees dtor))) rtod))) (println (str (atan (tan radians) ) " " (* (atan (tan (* degrees dtor))) rtod)))</lang>
Output: (matches that of Java)
0.7071067811865475 0.7071067811865475 0.7071067811865476 0.7071067811865476 0.9999999999999999 0.9999999999999999 0.7853981633974482 44.99999999999999 0.7853981633974483 45.0 0.7853981633974483 45.0
Common Lisp
<lang lisp>(defun deg->rad (x) (* x (/ pi 180))) (defun rad->deg (x) (* x (/ 180 pi)))
(mapc (lambda (x) (format t "~s => ~s~%" x (eval x)))
'((sin (/ pi 4)) (sin (deg->rad 45)) (cos (/ pi 6)) (cos (deg->rad 30)) (tan (/ pi 3)) (tan (deg->rad 60)) (asin 1) (rad->deg (asin 1)) (acos 1/2) (rad->deg (acos 1/2)) (atan 15) (rad->deg (atan 15))))</lang>
D
<lang d>import std.stdio, std.math;
void main() {
enum real degrees = 45.0; enum real t0 = degrees * PI / 180.0; writeln("Reference: 0.7071067811865475244008"); writefln("Sine: %.20f %.20f", sin(PI_4), sin(t0)); writefln("Cosine: %.20f %.20f", cos(PI_4), cos(t0)); writefln("Tangent: %.20f %.20f", tan(PI_4), tan(t0));
writeln(); writeln("Reference: 0.7853981633974483096156"); immutable real t1 = asin(sin(PI_4)); writefln("Arcsine: %.20f %.20f", t1, t1 * 180.0 / PI);
immutable real t2 = acos(cos(PI_4)); writefln("Arccosine: %.20f %.20f", t2, t2 * 180.0 / PI);
immutable real t3 = atan(tan(PI_4)); writefln("Arctangent: %.20f %.20f", t3, t3 * 180.0 / PI);
}</lang> Output:
Reference: 0.7071067811865475244008 Sine: 0.70710678118654752442 0.70710678118654752442 Cosine: 0.70710678118654752438 0.70710678118654752438 Tangent: 1.00000000000000000000 1.00000000000000000000 Reference: 0.7853981633974483096156 Arcsine: 0.78539816339744830970 45.00000000000000000400 Arccosine: 0.78539816339744830961 45.00000000000000000000 Arctangent: 0.78539816339744830961 45.00000000000000000000
E
<lang e>def pi := (-1.0).acos()
def radians := pi / 4.0 def degrees := 45.0
def d2r := (pi/180).multiply def r2d := (180/pi).multiply
println(`$\ ${radians.sin()} ${d2r(degrees).sin()} ${radians.cos()} ${d2r(degrees).cos()} ${radians.tan()} ${d2r(degrees).tan()} ${def asin := radians.sin().asin()} ${r2d(asin)} ${def acos := radians.cos().acos()} ${r2d(acos)} ${def atan := radians.tan().atan()} ${r2d(atan)} `)</lang>
Output:
0.7071067811865475 0.7071067811865475 0.7071067811865476 0.7071067811865476 0.9999999999999999 0.9999999999999999 0.7853981633974482 44.99999999999999 0.7853981633974483 45.0 0.7853981633974483 45.0
Erlang
<lang erlang> Deg=45. Rad=math:pi()/4.
math:sin(Deg * math:pi() / 180)==math:sin(Rad). </lang>
Output:
true
<lang erlang> math:cos(Deg * math:pi() / 180)==math:cos(Rad). </lang>
Output:
true
<lang erlang> math:tan(Deg * math:pi() / 180)==math:tan(Rad). </lang>
Output:
true
<lang erlang> Temp = math:acos(math:cos(Rad)). Temp * 180 / math:pi()==Deg. </lang>
Output:
true
<lang erlang> Temp = math:atan(math:tan(Rad)). Temp * 180 / math:pi()==Deg. </lang>
Output:
true
Fantom
Fantom's Float library includes all six trigonometric functions, which assume the number is in radians. Methods are provided to convert: toDegrees and toRadians.
<lang fantom> class Main {
public static Void main () { Float r := Float.pi / 4 echo (r.sin) echo (r.cos) echo (r.tan) echo (r.asin) echo (r.acos) echo (r.atan) // and from degrees echo (45.0f.toRadians.sin) echo (45.0f.toRadians.cos) echo (45.0f.toRadians.tan) echo (45.0f.toRadians.asin) echo (45.0f.toRadians.acos) echo (45.0f.toRadians.atan) }
} </lang>
Forth
<lang forth>45e pi f* 180e f/ \ radians
cr fdup fsin f. \ also available: fsincos ( r -- sin cos ) cr fdup fcos f. cr fdup ftan f. cr fdup fasin f. cr fdup facos f. cr fatan f. \ also available: fatan2 ( r1 r2 -- atan[r1/r2] )</lang>
Fortran
Trigonometic functions expect arguments in radians so degrees require conversion <lang fortran>PROGRAM Trig
REAL pi, dtor, rtod, radians, degrees pi = 4.0 * ATAN(1.0) dtor = pi / 180.0 rtod = 180.0 / pi radians = pi / 4.0 degrees = 45.0 WRITE(*,*) SIN(radians), SIN(degrees*dtor) WRITE(*,*) COS(radians), COS(degrees*dtor) WRITE(*,*) TAN(radians), TAN(degrees*dtor) WRITE(*,*) ASIN(SIN(radians)), ASIN(SIN(degrees*dtor))*rtod WRITE(*,*) ACOS(COS(radians)), ACOS(COS(degrees*dtor))*rtod WRITE(*,*) ATAN(TAN(radians)), ATAN(TAN(degrees*dtor))*rtod
END PROGRAM Trig</lang> Output:
0.707107 0.707107 0.707107 0.707107 1.00000 1.00000 0.785398 45.0000 0.785398 45.0000 0.785398 45.0000
The following trigonometric functions are also available <lang fortran>ATAN2(y,x) ! Arctangent(y/x), -pi < result <= +pi SINH(x) ! Hyperbolic sine COSH(x) ! Hyperbolic cosine TANH(x) ! Hyperbolic tangent</lang>
Go
The Go math package provides the constant pi and the six trigonometric functions called for by the task. The functions all use the float64 type and work in radians. It also provides a Sincos function. <lang go>package main
import (
"fmt" "math"
)
const d = 30. const r = d * math.Pi / 180
var s = .5 var c = math.Sqrt(3) / 2 var t = 1 / math.Sqrt(3)
func main() {
fmt.Printf("sin(%9.6f deg) = %f\n", d, math.Sin(d*math.Pi/180)) fmt.Printf("sin(%9.6f rad) = %f\n", r, math.Sin(r)) fmt.Printf("cos(%9.6f deg) = %f\n", d, math.Cos(d*math.Pi/180)) fmt.Printf("cos(%9.6f rad) = %f\n", r, math.Cos(r)) fmt.Printf("tan(%9.6f deg) = %f\n", d, math.Tan(d*math.Pi/180)) fmt.Printf("tan(%9.6f rad) = %f\n", r, math.Tan(r)) fmt.Printf("asin(%f) = %9.6f deg\n", s, math.Asin(s)*180/math.Pi) fmt.Printf("asin(%f) = %9.6f rad\n", s, math.Asin(s)) fmt.Printf("acos(%f) = %9.6f deg\n", c, math.Acos(c)*180/math.Pi) fmt.Printf("acos(%f) = %9.6f rad\n", c, math.Acos(c)) fmt.Printf("atan(%f) = %9.6f deg\n", t, math.Atan(t)*180/math.Pi) fmt.Printf("atan(%f) = %9.6f rad\n", t, math.Atan(t))
}</lang> Output:
sin(30.000000 deg) = 0.500000 sin( 0.523599 rad) = 0.500000 cos(30.000000 deg) = 0.866025 cos( 0.523599 rad) = 0.866025 tan(30.000000 deg) = 0.577350 tan( 0.523599 rad) = 0.577350 asin(0.500000) = 30.000000 deg asin(0.500000) = 0.523599 rad acos(0.866025) = 30.000000 deg acos(0.866025) = 0.523599 rad atan(0.577350) = 30.000000 deg atan(0.577350) = 0.523599 rad
Groovy
Trig functions use radians, degrees must be converted to/from radians <lang groovy>def radians = Math.PI/4 def degrees = 45
def d2r = { it*Math.PI/180 } def r2d = { it*180/Math.PI }
println "sin(\u03C0/4) = ${Math.sin(radians)} == sin(45\u00B0) = ${Math.sin(d2r(degrees))}" println "cos(\u03C0/4) = ${Math.cos(radians)} == cos(45\u00B0) = ${Math.cos(d2r(degrees))}" println "tan(\u03C0/4) = ${Math.tan(radians)} == tan(45\u00B0) = ${Math.tan(d2r(degrees))}" println "asin(\u221A2/2) = ${Math.asin(2**(-0.5))} == asin(\u221A2/2)\u00B0 = ${r2d(Math.asin(2**(-0.5)))}\u00B0" println "acos(\u221A2/2) = ${Math.acos(2**(-0.5))} == acos(\u221A2/2)\u00B0 = ${r2d(Math.acos(2**(-0.5)))}\u00B0" println "atan(1) = ${Math.atan(1)} == atan(1)\u00B0 = ${r2d(Math.atan(1))}\u00B0"</lang>
Output:
sin(π/4) = 0.7071067811865475 == sin(45°) = 0.7071067811865475 cos(π/4) = 0.7071067811865476 == cos(45°) = 0.7071067811865476 tan(π/4) = 0.9999999999999999 == tan(45°) = 0.9999999999999999 asin(√2/2) = 0.7853981633974482 == asin(√2/2)° = 44.99999999999999° acos(√2/2) = 0.7853981633974484 == acos(√2/2)° = 45.00000000000001° atan(1) = 0.7853981633974483 == atan(1)° = 45.0°
Haskell
Trigonometric functions use radians; degrees require conversion.
<lang haskell>fromDegrees deg = deg * pi / 180 toDegrees rad = rad * 180 / pi
example = [
sin (pi / 6), sin (fromDegrees 30), cos (pi / 6), cos (fromDegrees 30), tan (pi / 6), tan (fromDegrees 30), asin 0.5, toDegrees (asin 0.5), acos 0.5, toDegrees (acos 0.5), atan 0.5, toDegrees (atan 0.5)]</lang>
HicEst
Translated from Fortran: <lang hicest>pi = 4.0 * ATAN(1.0) dtor = pi / 180.0 rtod = 180.0 / pi radians = pi / 4.0 degrees = 45.0
WRITE(ClipBoard) SIN(radians), SIN(degrees*dtor) WRITE(ClipBoard) COS(radians), COS(degrees*dtor) WRITE(ClipBoard) TAN(radians), TAN(degrees*dtor) WRITE(ClipBoard) ASIN(SIN(radians)), ASIN(SIN(degrees*dtor))*rtod WRITE(ClipBoard) ACOS(COS(radians)), ACOS(COS(degrees*dtor))*rtod WRITE(ClipBoard) ATAN(TAN(radians)), ATAN(TAN(degrees*dtor))*rtod</lang> <lang hicest>0.7071067812 0.7071067812 0.7071067812 0.7071067812 1 1 0.7853981634 45 0.7853981634 45 0.7853981634 45</lang> SINH, COSH, TANH, and inverses are available as well.
IDL
<lang idl>deg = 35 ; arbitrary number of degrees rad = !dtor*deg ; system variables !dtor and !radeg convert between rad and deg</lang> <lang idl>; the trig functions receive and emit radians: print, rad, sin(rad), asin(sin(rad)) print, cos(rad), acos(cos(rad)) print, tan(rad), atan(tan(rad)) ; etc
- prints the following
- 0.610865 0.573576 0.610865
- 0.819152 0.610865
- 0.700208 0.610865</lang>
<lang idl>; the hyperbolic versions exist and behave as expected: print, sinh(rad) ; etc
- outputs
- 0.649572</lang>
<lang idl>;If the input is an array, the output has the same dimensions etc as the input: x = !dpi/[[2,3],[4,5],[6,7]] ; !dpi is a read-only sysvar = 3.1415... print,sin(x)
- outputs
- 1.0000000 0.86602540
- 0.70710678 0.58778525
- 0.50000000 0.43388374</lang>
<lang idl>; the trig functions behave as expected for complex arguments: x = complex(1,2) print,sin(x)
- outputs
- ( 3.16578, 1.95960)</lang>
Icon and Unicon
Icon and Unicon trig functions 'sin', 'cos', 'tan', 'asin', 'acos', and 'atan' operate on angles expressed in radians. Conversion functions 'dtor' and 'rtod' convert between the two systems. The example below uses string invocation to construct and call the functions:
Icon
<lang Icon>invocable all procedure main()
d := 30 # degrees r := dtor(d) # convert to radians
every write(f := !["sin","cos","tan"],"(",r,")=",y := f(r)," ",fi := "a" || f,"(",y,")=",x := fi(y)," rad = ",rtod(x)," deg") end</lang>
Sample Output:
sin(0.5235987755982988)=0.4999999999999999 asin(0.4999999999999999)=0.5235987755982988 rad = 30.0 deg cos(0.5235987755982988)=0.8660254037844387 acos(0.8660254037844387)=0.5235987755982987 rad = 29.99999999999999 deg tan(0.5235987755982988)=0.5773502691896257 atan(0.5773502691896257)=0.5235987755982988 rad = 30.0 deg
Unicon
The Icon solution works in Unicon.
J
The circle functions in J include trigonometric functions. Native operation is in radians, so values in degrees involve conversion.
Sine, cosine, and tangent of a single angle, indicated as pi-over-four radians and as 45 degrees: <lang j> >,:(1&o. ; 2&o. ; 3&o.) (4%~o. 1), 180%~o. 45</lang>
0.707107 0.707107 0.707107 0.707107 1 1
Arcsine, arccosine, and arctangent of one-half, in radians and degrees: <lang j> >,:([ , 180p_1&*)&.> (_1&o. ; _2&o. ; _3&o.) 0.5</lang>
0.523599 30 1.0472 60 0.463648 26.5651
Java
Java's Math class contains all six functions and is automatically included as part of the language. The functions all accept radians only, so conversion is necessary when dealing with degrees. The Math class also has a PI constant for easy conversion.
<lang java>public class Trig {
public static void main(String[] args) { //Pi / 4 is 45 degrees. All answers should be the same. double radians = Math.PI / 4; double degrees = 45.0; //sine System.out.println(Math.sin(radians) + " " + Math.sin(Math.toRadians(degrees))); //cosine System.out.println(Math.cos(radians) + " " + Math.cos(Math.toRadians(degrees))); //tangent System.out.println(Math.tan(radians) + " " + Math.tan(Math.toRadians(degrees))); //arcsine double arcsin = Math.asin(Math.sin(radians)); System.out.println(arcsin + " " + Math.toDegrees(arcsin)); //arccosine double arccos = Math.acos(Math.cos(radians)); System.out.println(arccos + " " + Math.toDegrees(arccos)); //arctangent double arctan = Math.atan(Math.tan(radians)); System.out.println(arctan + " " + Math.toDegrees(arctan)); }
}</lang>
Output:
0.7071067811865475 0.7071067811865475 0.7071067811865476 0.7071067811865476 0.9999999999999999 0.9999999999999999 0.7853981633974482 44.99999999999999 0.7853981633974483 45.0 0.7853981633974483 45.0
JavaScript
JavaScript's Math class contains all six functions and is automatically included as part of the language. The functions all accept radians only, so conversion is necessary when dealing with degrees. The Math class also has a PI constant for easy conversion.
<lang javascript>var
radians = Math.PI / 4, // Pi / 4 is 45 degrees. All answers should be the same. degrees = 45.0, sine = Math.sin(radians), cosine = Math.cos(radians), tangent = Math.tan(radians), arcsin = Math.asin(sine), arccos = Math.acos(cosine), arctan = Math.atan(tangent);
// sine window.alert(sine + " " + Math.sin(degrees * Math.PI / 180)); // cosine window.alert(cosine + " " + Math.cos(degrees * Math.PI / 180)); // tangent window.alert(tangent + " " + Math.tan(degrees * Math.PI / 180)); // arcsine window.alert(arcsin + " " + (arcsin * 180 / Math.PI)); // arccosine window.alert(arccos + " " + (arccos * 180 / Math.PI)); // arctangent window.alert(arctan + " " + (arctan * 180 / Math.PI));</lang>
Liberty BASIC
<lang lb>' [RC] Trigonometric functions.
' Liberty Basic works in radians. All six functions are available. ' Optional information. You may-- ' 1. Run as is, for fixed 45 degree 'input'. ' 2. Put other degrees ( 0 to 90) into line 2. ( For '90', the tangent = infinity. ) ' 3. 'Shorten' decimal places for less accuracy. ' 4. Put radians into line 4. ( 0 to 1.5707963267948966 ). Just delete the 'rem', ' by the Rad example. Now, line 4 data will replace line 2 and 3 data. 2 Deg = 45 3 Rad = Deg / 57.295779513082343 4 rem Rad = 1.27 print "When the angle = "; using("####.###", (Rad) * 57.29577951); " degrees," print " (or"; using("###.###############", Rad);" radians), then --" print print using( "####.###############", sin( Rad)); " = sine" print using( "####.###############", cos( Rad)); " = cosine" print using( "####.##############", tan( Rad)); " = tangent" print print " Now the inverses --" print "For the 'sine' above, the 'arcsine' is --"; print using("####.####", (asn ( sin ( Rad))) * 57.29577951) ; " degrees" print " ( or," ; using("####.###############",asn ( sin ( Rad)));" radians ) " print "For the 'cosine' above, the 'arccosine' is --"; print using("####.####", (acs ( cos ( Rad))) * 57.29577951) ; " degrees" print " ( or," ; using("####.###############",acs ( cos ( Rad)));" radians ) " print "For the 'tangent' above, the 'arctangent' is --"; print using("####.####", (atn ( tan ( Rad))) * 57.29577951) ; " degrees" print " ( or," ; using("####.###############",atn ( tan ( Rad)));" radians ) "
end
'----------- Output ------------- 'When the angle = 45.000 degrees, ' (or 0.785398163397448 radians), then -- ' ' 0.707106781186547 = sine ' 0.707106781186548 = cosine ' 1.00000000000000 = tangent ' ' Now the inverses -- 'For the 'sine' above, the 'arcsine' is -- 45.0000 degrees ' ( or, 0.785398163397448 radians ) 'For the 'cosine' above, the 'arccosine' is -- 45.0000 degrees ' ( or, 0.785398163397448 radians ) 'For the 'tangent' above, the 'arctangent' is -- 45.0000 degrees ' ( or, 0.785398163397448 radians )
end function</lang>
Logo
UCB Logo has sine, cosine, and arctangent; each having variants for degrees or radians. <lang logo>print sin 45 print cos 45 print arctan 1 make "pi (radarctan 0 1) * 2 ; based on quadrant if uses two parameters print radsin :pi / 4 print radcos :pi / 4 print 4 * radarctan 1</lang>
Lhogho has pi defined in its trigonometric functions. Otherwise the same as UCB Logo.
<lang logo>print sin 45
print cos 45
print arctan 1
print radsin pi / 4
print radcos pi / 4
print 4 * radarctan 1</lang>
Lua
<lang lua>print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4))</lang>
Mathematica
<lang Mathematica>Sin[1] Cos[1] Tan[1] ArcSin[1] ArcCos[1] ArcTan[1] Sin[90 Degree] Cos[90 Degree] Tan[90 Degree] </lang>
MATLAB
A full list of built-in trig functions can be found in the MATLAB Documentation.
<lang MATLAB>function trigExample(angleDegrees)
angleRadians = angleDegrees * (pi/180); disp(sprintf('sin(%f)= %f\nasin(%f)= %f',[angleRadians sin(angleRadians) sin(angleRadians) asin(sin(angleRadians))])); disp(sprintf('sind(%f)= %f\narcsind(%f)= %f',[angleDegrees sind(angleDegrees) sind(angleDegrees) asind(sind(angleDegrees))])); disp('-----------------------'); disp(sprintf('cos(%f)= %f\nacos(%f)= %f',[angleRadians cos(angleRadians) cos(angleRadians) acos(cos(angleRadians))])); disp(sprintf('cosd(%f)= %f\narccosd(%f)= %f',[angleDegrees cosd(angleDegrees) cosd(angleDegrees) acosd(cosd(angleDegrees))])); disp('-----------------------'); disp(sprintf('tan(%f)= %f\natan(%f)= %f',[angleRadians tan(angleRadians) tan(angleRadians) atan(tan(angleRadians))])); disp(sprintf('tand(%f)= %f\narctand(%f)= %f',[angleDegrees tand(angleDegrees) tand(angleDegrees) atand(tand(angleDegrees))]));
end</lang>
Sample Output: <lang MATLAB>>> trigExample(78) sin(1.361357)= 0.978148 asin(0.978148)= 1.361357 sind(78.000000)= 0.978148 arcsind(0.978148)= 78.000000
cos(1.361357)= 0.207912 acos(0.207912)= 1.361357 cosd(78.000000)= 0.207912 arccosd(0.207912)= 78.000000
tan(1.361357)= 4.704630 atan(4.704630)= 1.361357 tand(78.000000)= 4.704630 arctand(4.704630)= 78.000000</lang>
MAXScript
Maxscript trigonometric functions accept degrees only. The built-ins degToRad and radToDeg allow easy conversion. <lang maxscript>local radians = pi / 4 local degrees = 45.0
--sine print (sin (radToDeg radians)) print (sin degrees) --cosine print (cos (radToDeg radians)) print (cos degrees) --tangent print (tan (radToDeg radians)) print (tan degrees) --arcsine print (asin (sin (radToDeg radians))) print (asin (sin degrees)) --arccosine print (acos (cos (radToDeg radians))) print (acos (cos degrees)) --arctangent print (atan (tan (radToDeg radians))) print (atan (tan degrees))</lang>
Metafont
Metafont has sind
and cosd
, which compute sine and cosine of an angle expressed in degree. We need to define the rest.
<lang metafont>Pi := 3.14159; vardef torad expr x = Pi*x/180 enddef; % conversions vardef todeg expr x = 180x/Pi enddef; vardef sin expr x = sind(todeg(x)) enddef; % radians version of sind vardef cos expr x = cosd(todeg(x)) enddef; % and cosd
vardef sign expr x = if x>=0: 1 else: -1 fi enddef; % commodity
vardef tand expr x = % tan with arg in degree
if cosd(x) = 0: infinity * sign(sind(x)) else: sind(x)/cosd(x) fi enddef;
vardef tan expr x = tand(todeg(x)) enddef; % arg in rad
% INVERSE
% the arc having x as tanget is that between x-axis and a line % from the center to the point (1, x); MF angle says this vardef atand expr x = angle(1,x) enddef; vardef atan expr x = torad(atand(x)) enddef; % rad version
% known formula to express asin and acos in function of % atan; a+-+b stays for sqrt(a^2 - b^2) (defined in plain MF) vardef asin expr x = 2atan(x/(1+(1+-+x))) enddef; vardef acos expr x = 2atan((1+-+x)/(1+x)) enddef;
vardef asind expr x = todeg(asin(x)) enddef; % degree versions vardef acosd expr x = todeg(acos(x)) enddef;
% commodity def outcompare(expr a, b) = message decimal a & " = " & decimal b enddef;
% output tests outcompare(torad(60), Pi/3); outcompare(todeg(Pi/6), 30);
outcompare(Pi/3, asin(sind(60))); outcompare(30, acosd(cos(Pi/6))); outcompare(45, atand(tand(45))); outcompare(Pi/4, atan(tand(45)));
outcompare(sin(Pi/3), sind(60)); outcompare(cos(Pi/4), cosd(45)); outcompare(tan(Pi/3), tand(60));
end</lang>
OCaml
OCaml's preloaded Pervasives module contains all six functions. The functions all accept radians only, so conversion is necessary when dealing with degrees. <lang ocaml>let pi = 4. *. atan 1.
let radians = pi /. 4. let degrees = 45.;;
Printf.printf "%f %f\n" (sin radians) (sin (degrees *. pi /. 180.));; Printf.printf "%f %f\n" (cos radians) (cos (degrees *. pi /. 180.));; Printf.printf "%f %f\n" (tan radians) (tan (degrees *. pi /. 180.));; let arcsin = asin (sin radians);; Printf.printf "%f %f\n" arcsin (arcsin *. 180. /. pi);; let arccos = acos (cos radians);; Printf.printf "%f %f\n" arccos (arccos *. 180. /. pi);; let arctan = atan (tan radians);; Printf.printf "%f %f\n" arctan (arctan *. 180. /. pi);;</lang> Output:
0.707107 0.707107 0.707107 0.707107 1.000000 1.000000 0.785398 45.000000 0.785398 45.000000 0.785398 45.000000
Octave
<lang octave>function d = degree(rad)
d = 180*rad/pi;
endfunction
r = pi/3; rd = degree(r);
funcs = { "sin", "cos", "tan", "sec", "cot", "csc" }; ifuncs = { "asin", "acos", "atan", "asec", "acot", "acsc" };
for i = 1 : numel(funcs)
v = arrayfun(funcs{i}, r); vd = arrayfun(strcat(funcs{i}, "d"), rd); iv = arrayfun(ifuncs{i}, v); ivd = arrayfun(strcat(ifuncs{i}, "d"), vd); printf("%s(%f) = %s(%f) = %f (%f)\n", funcs{i}, r, strcat(funcs{i}, "d"), rd, v, vd); printf("%s(%f) = %f\n%s(%f) = %f\n", ifuncs{i}, v, iv, strcat(ifuncs{i}, "d"), vd, ivd);
endfor</lang>
Output:
sin(1.047198) = sind(60.000000) = 0.866025 (0.866025) asin(0.866025) = 1.047198 asind(0.866025) = 60.000000 cos(1.047198) = cosd(60.000000) = 0.500000 (0.500000) acos(0.500000) = 1.047198 acosd(0.500000) = 60.000000 tan(1.047198) = tand(60.000000) = 1.732051 (1.732051) atan(1.732051) = 1.047198 atand(1.732051) = 60.000000 sec(1.047198) = secd(60.000000) = 2.000000 (2.000000) asec(2.000000) = 1.047198 asecd(2.000000) = 60.000000 cot(1.047198) = cotd(60.000000) = 0.577350 (0.577350) acot(0.577350) = 1.047198 acotd(0.577350) = 60.000000 csc(1.047198) = cscd(60.000000) = 1.154701 (1.154701) acsc(1.154701) = 1.047198 acscd(1.154701) = 60.000000
(Lacking in this code but present in GNU Octave: sinh, cosh, tanh, coth and inverses)
Oz
<lang oz>declare
PI = 3.14159265
fun {FromDegrees Deg} Deg * PI / 180. end
fun {ToDegrees Rad} Rad * 180. / PI end
Radians = PI / 4. Degrees = 45.
in
for F in [Sin Cos Tan] do {System.showInfo {F Radians}#" "#{F {FromDegrees Degrees}}} end
for I#F in [Asin#Sin Acos#Cos Atan#Tan] do {System.showInfo {I {F Radians}}#" "#{ToDegrees {I {F Radians}}}} end</lang>
PARI/GP
Pari accepts only radians; the conversion is simple but not included here. <lang parigp>cos(Pi/2) sin(Pi/2) tan(Pi/2) acos(1) asin(1) atan(1)</lang>
Pascal
<lang pascal>Program TrigonometricFuntions(output);
uses
math;
var
radians, degree: double;
begin
radians := pi / 4.0; degree := 45; writeln (sin(radians), sin(degree/180*pi)); writeln (cos(radians), cos(degree/180*pi)); writeln (tan(radians), tan(degree/180*pi)); writeln (arcsin(sin(radians))*4/pi, arcsin(sin(degree/180*pi))/pi*180); writeln (arccos(cos(radians))*4/pi, arccos(cos(degree/180*pi))/pi*180); writeln (arctan(tan(radians))*4/pi, arctan(tan(degree/180*pi))/pi*180);
end.</lang> Output:
% ./TrigonometricFunctions 7.0710678118654750E-0001 7.0710678118654752E-0001 7.0710678118654755E-0001 7.0710678118654752E-0001 9.9999999999999994E-0001 1.0000000000000000E+0000 9.9999999999999996E-0001 4.5000000000000000E+0001 9.9999999999999996E-0001 4.5000000000000000E+0001 9.9999999999999996E-0001 4.5000000000000000E+0001
Perl
<lang perl>use Math::Trig;
my $angle_degrees = 45; my $angle_radians = pi / 4;
print sin($angle_radians), ' ', sin(deg2rad($angle_degrees)), "\n"; print cos($angle_radians), ' ', cos(deg2rad($angle_degrees)), "\n"; print tan($angle_radians), ' ', tan(deg2rad($angle_degrees)), "\n"; print cot($angle_radians), ' ', cot(deg2rad($angle_degrees)), "\n"; my $asin = asin(sin($angle_radians)); print $asin, ' ', rad2deg($asin), "\n"; my $acos = acos(cos($angle_radians)); print $acos, ' ', rad2deg($acos), "\n"; my $atan = atan(tan($angle_radians)); print $atan, ' ', rad2deg($atan), "\n"; my $acot = acot(cot($angle_radians)); print $acot, ' ', rad2deg($acot), "\n";</lang>
Output:
0.707106781186547 0.707106781186547 0.707106781186548 0.707106781186548 1 1 1 1 0.785398163397448 45 0.785398163397448 45 0.785398163397448 45 0.785398163397448 45
Perl 6
<lang perl6>say sin(pi/3), ' ', sin 60, 'd'; # 'g' (gradians) and 1 (circles) say cos(pi/4), ' ', cos 45, 'd'; # are also recognized. say tan(pi/6), ' ', tan 30, 'd';
say asin(sqrt(3)/2), ' ', asin sqrt(3)/2, 'd'; say acos(1/sqrt 2), ' ', acos 1/sqrt(2), 'd'; say atan(1/sqrt 3), ' ', atan 1/sqrt(3), 'd';</lang>
PL/I
<lang PL/I> declare (x, xd, y, v) float;
x = 0.5; xd = 45;
/* angle in radians: */ v = sin(x); y = asin(v); put skip list (y); v = cos(x); y = acos(v); put skip list (y); v = tan(x); y = atan(v); put skip list (y);
/* angle in degrees: */ v = sind(xd); put skip list (v); v = cosd(xd); put skip list (v); v = tand(xd); y = atand(v); put skip list (y);
/* hyperbolic functions: */ v = sinh(x); put skip list (v); v = cosh(x); put skip list (v); v = tanh(x); y = atanh(v); put skip list (y); </lang>
PL/SQL
The transcendental functions COS, COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, and TANH are accurate to 36 decimal digits. The transcendental functions ACOS, ASIN, ATAN, and ATAN2 are accurate to 30 decimal digits.
<lang plsql>DECLARE
pi NUMBER := 4 * atan(1); radians NUMBER := pi / 4; degrees NUMBER := 45.0;
BEGIN
DBMS_OUTPUT.put_line(SIN(radians) || ' ' || SIN(degrees * pi/180) ); DBMS_OUTPUT.put_line(COS(radians) || ' ' || COS(degrees * pi/180) ); DBMS_OUTPUT.put_line(TAN(radians) || ' ' || TAN(degrees * pi/180) ); DBMS_OUTPUT.put_line(ASIN(SIN(radians)) || ' ' || ASIN(SIN(degrees * pi/180)) * 180/pi); DBMS_OUTPUT.put_line(ACOS(COS(radians)) || ' ' || ACOS(COS(degrees * pi/180)) * 180/pi); DBMS_OUTPUT.put_line(ATAN(TAN(radians)) || ' ' || ATAN(TAN(degrees * pi/180)) * 180/pi);
end;</lang>
Output:
,7071067811865475244008443621048490392889 ,7071067811865475244008443621048490392893 ,7071067811865475244008443621048490392783 ,7071067811865475244008443621048490392779 1,00000000000000000000000000000000000001 1,00000000000000000000000000000000000002 ,7853981633974483096156608458198656891236 44,99999999999999999999999999999942521259 ,7853981633974483096156608458198857529988 45,00000000000000000000000000000057478811 ,7853981633974483096156608458198757210578 45,00000000000000000000000000000000000067
The following trigonometric functions are also available <lang plsql>ATAN2(n1,n2) --Arctangent(y/x), -pi < result <= +pi SINH(n) --Hyperbolic sine COSH(n) --Hyperbolic cosine TANH(n) --Hyperbolic tangent</lang>
PHP
<lang php>$radians = M_PI / 4; $degrees = 45 * M_PI / 180; echo sin($radians) . " " . sin($degrees); echo cos($radians) . " " . cos($degrees); echo tan($radians) . " " . tan($degrees); echo asin(sin($radians)) . " " . asin(sin($radians)) * 180 / M_PI; echo acos(cos($radians)) . " " . acos(cos($radians)) * 180 / M_PI; echo atan(tan($radians)) . " " . atan(tan($radians)) * 180 / M_PI;</lang>
PicoLisp
<lang PicoLisp>(load "@lib/math.l")
(de dtor (Deg)
(*/ Deg pi 180.0) )
(de rtod (Rad)
(*/ Rad 180.0 pi) )
(prinl
(format (sin (/ pi 4)) *Scl) " " (format (sin (dtor 45.0)) *Scl) )
(prinl
(format (cos (/ pi 4)) *Scl) " " (format (cos (dtor 45.0)) *Scl) )
(prinl
(format (tan (/ pi 4)) *Scl) " " (format (tan (dtor 45.0)) *Scl) )
(prinl
(format (asin (sin (/ pi 4))) *Scl) " " (format (rtod (asin (sin (dtor 45.0)))) *Scl) )
(prinl
(format (acos (cos (/ pi 4))) *Scl) " " (format (rtod (acos (cos (dtor 45.0)))) *Scl) )
(prinl
(format (atan (tan (/ pi 4))) *Scl) " " (format (rtod (atan (tan (dtor 45.0)))) *Scl) )</lang>
Output:
0.707107 0.707107 0.707107 0.707107 1.000000 1.000000 0.785398 44.999986 0.785398 44.999986 0.785398 44.999986
Pop11
Pop11 trigonometric functions accept both degrees and radians. In default mode argument is in degrees, after setting 'popradians' flag to 'true' arguments are in radians.
<lang pop11>sin(30) => cos(45) => tan(45) => arcsin(0.7) => arccos(0.7) => arctan(0.7) =>
- switch to radians
true -> popradians;
sin(pi*30/180) => cos(pi*45/180) => tan(pi*45/180) => arcsin(0.7) => arccos(0.7) => arctan(0.7) =></lang>
PostScript
<lang postscript> 90 sin =
60 cos =
%tan of 45 degrees
45 sin 45 cos div =
%inverse tan ( arc tan of sqrt 3)
3 sqrt 1 atan = </lang> Output
1.0 0.5 1.0 60.0
PowerShell
<lang powershell>$rad = [Math]::PI / 4 $deg = 45 '{0,10} {1,10}' -f 'Radians','Degrees' '{0,10:N6} {1,10:N6}' -f [Math]::Sin($rad), [Math]::Sin($deg * [Math]::PI / 180) '{0,10:N6} {1,10:N6}' -f [Math]::Cos($rad), [Math]::Cos($deg * [Math]::PI / 180) '{0,10:N6} {1,10:N6}' -f [Math]::Tan($rad), [Math]::Tan($deg * [Math]::PI / 180) $temp = [Math]::Asin([Math]::Sin($rad)) '{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) $temp = [Math]::Acos([Math]::Cos($rad)) '{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) $temp = [Math]::Atan([Math]::Tan($rad)) '{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI)</lang> Output:
Radians Degrees 0,707107 0,707107 0,707107 0,707107 1,000000 1,000000 0,785398 45,000000 0,785398 45,000000 0,785398 45,000000
PureBasic
<lang purebasic>OpenConsole()
Macro DegToRad(deg)
deg*#PI/180
EndMacro Macro RadToDeg(rad)
rad*180/#PI
EndMacro
degree = 45 radians.f = #PI/4
PrintN(StrF(Sin(DegToRad(degree)))+" "+StrF(Sin(radians))) PrintN(StrF(Cos(DegToRad(degree)))+" "+StrF(Cos(radians))) PrintN(StrF(Tan(DegToRad(degree)))+" "+StrF(Tan(radians)))
arcsin.f = ASin(Sin(radians)) PrintN(StrF(arcsin)+" "+Str(RadToDeg(arcsin))) arccos.f = ACos(Cos(radians)) PrintN(StrF(arccos)+" "+Str(RadToDeg(arccos))) arctan.f = ATan(Tan(radians)) PrintN(StrF(arctan)+" "+Str(RadToDeg(arctan)))
Input()</lang>
Output:
0.707107 0.707107 0.707107 0.707107 1.000000 1.000000 0.785398 45 0.785398 45 0.785398 45
Python
Python's math module contains all six functions. The functions all accept radians only, so conversion is necessary when dealing with degrees. The math module also has degrees() and radians() functions for easy conversion.
<lang python>Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> from math import degrees, radians, sin, cos, tan, asin, acos, atan, pi >>> rad, deg = pi/4, 45.0 >>> print("Sine:", sin(rad), sin(radians(deg))) Sine: 0.7071067811865475 0.7071067811865475 >>> print("Cosine:", cos(rad), cos(radians(deg))) Cosine: 0.7071067811865476 0.7071067811865476 >>> print("Tangent:", tan(rad), tan(radians(deg))) Tangent: 0.9999999999999999 0.9999999999999999 >>> arcsine = asin(sin(rad)) >>> print("Arcsine:", arcsine, degrees(arcsine)) Arcsine: 0.7853981633974482 44.99999999999999 >>> arccosine = acos(cos(rad)) >>> print("Arccosine:", arccosine, degrees(arccosine)) Arccosine: 0.7853981633974483 45.0 >>> arctangent = atan(tan(rad)) >>> print("Arctangent:", arctangent, degrees(arctangent)) Arctangent: 0.7853981633974483 45.0 >>> </lang>
R
<lang R>deg <- function(radians) 180*radians/pi rad <- function(degrees) degrees*pi/180 sind <- function(ang) sin(rad(ang)) cosd <- function(ang) cos(rad(ang)) tand <- function(ang) tan(rad(ang)) asind <- function(v) deg(asin(v)) acosd <- function(v) deg(acos(v)) atand <- function(v) deg(atan(v))
r <- pi/3 rd <- deg(r)
print( c( sin(r), sind(rd)) ) print( c( cos(r), cosd(rd)) ) print( c( tan(r), tand(rd)) )
S <- sin(pi/4) C <- cos(pi/3) T <- tan(pi/4)
print( c( asin(S), asind(S) ) ) print( c( acos(C), acosd(C) ) ) print( c( atan(T), atand(T) ) )</lang>
REBOL
<lang REBOL>REBOL [ Title: "Trigonometric Functions" Author: oofoe Date: 2009-12-07 URL: http://rosettacode.org/wiki/Trigonometric_Functions ]
radians: pi / 4 degrees: 45.0
- Unlike most languages, REBOL's trig functions work in degrees unless
- you specify differently.
print [sine/radians radians sine degrees] print [cosine/radians radians cosine degrees] print [tangent/radians radians tangent degrees]
d2r: func [ "Convert degrees to radians." d [number!] "Degrees" ][d * pi / 180]
arcsin: arcsine sine degrees print [d2r arcsin arcsin]
arccos: arccosine cosine degrees print [d2r arccos arccos]
arctan: arctangent tangent degrees print [d2r arctan arctan]</lang>
Output:
0.707106781186547 0.707106781186547 0.707106781186548 0.707106781186548 1.0 1.0 0.785398163397448 45.0 0.785398163397448 45.0 0.785398163397448 45.0
REXX
The REXX language doesn't have any trig functions (or for that matter, a square root [SQRT] function), so if higher math
functions are wanted, you have to roll your own. Some of the normal/regular trigonometric functions are included here.
<lang rexx> ┌──────────────────────────────────────────────────────────────────────────┐
│ One common method that ensures enough accuracy in REXX is specifying │ │ more precision (via NUMERIC DIGITS nnn) than is needed, and │ │ displaying the number of digits that is desired, or the number(s) │ │ could be re-normalized using the FORMAT bif. │ │ │ │ The technique used (below) is to set the numeric digits ten higher │ │ than the desired digits, as specified by the SHOWDIGS variable. │ └──────────────────────────────────────────────────────────────────────────┘</lang>
Most math (POW, EXP, LOG, LN, GAMMA, etc.), trigonometic, and hyperbolic functions need only five extra digits, but ten
extra digits is safer in case the argument is close to an asymptotic point or a multiple or fractional part of pi or somesuch.
It should also be noted that both the pi and e constants have only around 77 decimal digits as included here, if more
precision is needed, those constants should be extended. Both pi and e could've been shown with more precision,
but having large precision numbers would add to this REXX program's length. If anybody wishes to see this REXX version of
extended digits for pi or e, I could extend them to any almost any precision (as a REXX constant). Normally, a REXX
(external) subroutine is used for such purposes so as to not make the program using the constant unwieldly large.
<lang rexx>/*REXX program demonstrates some common trig functions (30 digits shown)*/
showdigs=30 /*show only 30 digits of number. */
numeric digits showdigs+10 /*DIGITS default is 9, but use */
/*extra digs to prevent rounding.*/
say 'Using' showdigs 'decimal digits precision.'; say
do j=-180 to +180 by 15 /*let's just do a half-Monty. */ stuff = right(j,4) 'degrees, rads='show( d2r(j)), ' sin='show(sinD(j)), ' cos='show(cosD(J)) /*don't let TAN go postal.*/ if abs(j)\==90 then stuff=stuff ' tan='show(tanD(j)) say stuff end /*j*/
say; do k=-1 to +1 by 1/2 /*keep the Arc-functions happy. */
say right(k,4) 'radians, degs='show( r2d(k)), ' Acos='show(Acos(k)), ' Asin='show(Asin(k)), ' Atan='show(Atan(k)) end /*k*/
exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────subroutines─────────────────────────*/ Asin: procedure; arg x; if x<-1 | x>1 then call AsinErr; s=x*x
if abs(x)>=.7 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end return z
Atan: procedure; arg x; if abs(x)=1 then return pi()/4*sign(x)
return Asin(x/sqrt(1+x**2))
cos: procedure; arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9)
if a=pi() then return -1; if a=pi()/2 | a=2*pi() then return 0 if a=pi()/3 then return .5; if a=2*pi()/3 then return -.5 return .sinCos(1,1,-1)
sin: procedure; arg x; x=r2r(x); numeric fuzz min(5,digits()-3)
if abs(x)=pi() then return 0; return .sinCos(x,x,1)
.sinCos: parse arg z 1 p,_,i; x=x*x
do k=2 by 2; _=-_*x/(k*(k+i));z=z+_;if z=p then leave;p=z;end; return z
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits();numeric digits 11
g=.sqrtGuess(); do j=0 while p>9; m.j=p; p=p%2+1; end do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end numeric digits d; return g/1
.sqrtGuess: if x<0 then call sqrtErr; numeric form; m.=11; p=d+d%4+2
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2
e: return, 2.7182818284590452353602874713526624977572470936999595749669676277240766303535
/*Note: the "real: E subroutine returns E's accuracy that */ /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ /*If more than 1 million digits are required, be patient. */
exp: procedure; arg x; ix=x%1; if abs(x-ix)>.5 then ix=ix+sign(x); x=x-ix
z=1; _=1; w=z; do j=1; _=_*x/j; z=(z+_)/1; if z==w then leave; w=z; end if z\==0 then z=z*e()**ix; return z
pi: return, /*a bit of overkill, but hey !! */ 3.1415926535897932384626433832795028841971693993751058209749445923078164062862
/*Note: the real PI subroutine returns PI's accuracy that */ /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ /*John Machin's formula is used for calculating more digits. */ /*If more than 1 million digits are required, be patient. */
Acos: procedure; arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x) AcosD: return r2d(Acos(arg(1))) AsinD: return r2d(Asin(arg(1))) cosD: return cos(d2r(arg(1))) sinD: return sin(d2r(arg(1))) tan: procedure; arg x; _=cos(x); if _=0 then call tanErr; return sin(x)/_ tanD: return tan(d2r(arg(1))) d2d: return arg(1)//360 /*normalize degrees►1 unit circle*/ d2r: return r2r(arg(1)*pi()/180) /*convert degrees ──► radians. */ r2d: return d2d((arg(1)*180/pi())) /*convert radians ──► degrees. */ r2r: return arg(1)//(2*pi()) /*normalize radians►1 unit circle*/ show: return left(left(,arg(1)>=0)format(arg(1),,showdigs)/1,showdigs) tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 tanErr: call tellErr 'tan('||x") causes division by zero, X="||x AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X='||x AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X='||x sqrtErr: call tellErr "sqrt(x), X can't be negative, X="||x
/* ┌───────────────────────────────────────────────────────────────┐ │ Not included here are: (among others): │ │ some of the usual higher-math functions normally associated │ │ with trig functions: POW, GAMMA, LGGAMMA, ERF, ERFC, ROOT, │ │ LOG (LN), LOG2, LOG10, ATAN2, │ │ all of the hyperbolic trig functions and their inverses, │ │ (too many to name here). │ │ Angle conversions/normalizations: degrees/radians/grads/mils │ │ [a circle = 2 pi radians, 360 degrees, 400 grads, 6400 mils].│ │ Some of the other trig functions (hypens added intentially): │ │ CHORD │ │ COT (co-tangent) │ │ CSC (co-secant) │ │ CVC (co-versed cosine) │ │ CVS (co-versed sine) │ │ CXS (co-exsecant) │ │ HAC (haver-cosine) │ │ HAV (haver-sine │ │ SEC (secant) │ │ VCS (versed cosine or vercosine) │ │ VSN (versed sine or versine) │ │ XCS (exsecant) │ │ COS/SIN/TAN cardinal (damped COS/SIN/TAN function) │ │ COS/SIN integral │ │ and all pertinent of the above's inverses (AVSN, ACVS...) │ └───────────────────────────────────────────────────────────────┘ */</lang>
output
Using 30 decimal digits precision. -180 degrees, rads=-3.141592653589793238462643383 sin= 0 cos=-1 tan= 0 -165 degrees, rads=-2.879793265790643801924089768 sin=-0.258819045102520762348898837 cos=-0.965925826289068286749743199 tan= 0.267949192431122706472553658 -150 degrees, rads=-2.617993877991494365385536152 sin=-0.5 cos=-0.866025403784438646763723170 tan= 0.577350269189625764509148780 -135 degrees, rads=-2.356194490192344928846982537 sin=-0.707106781186547524400844362 cos=-0.707106781186547524400844362 tan= 1 -120 degrees, rads=-2.094395102393195492308428922 sin=-0.866025403784438646763723170 cos=-0.5 tan= 1.732050807568877293527446341 -105 degrees, rads=-1.832595714594046055769875306 sin=-0.965925826289068286749743199 cos=-0.258819045102520762348898837 tan= 3.732050807568877293527446341 -90 degrees, rads=-1.570796326794896619231321691 sin=-1 cos= 0 -75 degrees, rads=-1.308996938995747182692768076 sin=-0.965925826289068286749743199 cos= 0.258819045102520762348898837 tan=-3.732050807568877293527446341 -60 degrees, rads=-1.047197551196597746154214461 sin=-0.866025403784438646763723170 cos= 0.5 tan=-1.732050807568877293527446341 -45 degrees, rads=-0.785398163397448309615660845 sin=-0.707106781186547524400844362 cos= 0.707106781186547524400844362 tan=-1 -30 degrees, rads=-0.523598775598298873077107230 sin=-0.5 cos= 0.866025403784438646763723170 tan=-0.577350269189625764509148780 -15 degrees, rads=-0.261799387799149436538553615 sin=-0.258819045102520762348898837 cos= 0.965925826289068286749743199 tan=-0.267949192431122706472553658 0 degrees, rads= 0 sin= 0 cos= 1 tan= 0 15 degrees, rads= 0.261799387799149436538553615 sin= 0.258819045102520762348898837 cos= 0.965925826289068286749743199 tan= 0.267949192431122706472553658 30 degrees, rads= 0.523598775598298873077107230 sin= 0.5 cos= 0.866025403784438646763723170 tan= 0.577350269189625764509148780 45 degrees, rads= 0.785398163397448309615660845 sin= 0.707106781186547524400844362 cos= 0.707106781186547524400844362 tan= 1 60 degrees, rads= 1.047197551196597746154214461 sin= 0.866025403784438646763723170 cos= 0.5 tan= 1.732050807568877293527446341 75 degrees, rads= 1.308996938995747182692768076 sin= 0.965925826289068286749743199 cos= 0.258819045102520762348898837 tan= 3.732050807568877293527446341 90 degrees, rads= 1.570796326794896619231321691 sin= 1 cos= 0 105 degrees, rads= 1.832595714594046055769875306 sin= 0.965925826289068286749743199 cos=-0.258819045102520762348898837 tan=-3.732050807568877293527446341 120 degrees, rads= 2.094395102393195492308428922 sin= 0.866025403784438646763723170 cos=-0.5 tan=-1.732050807568877293527446341 135 degrees, rads= 2.356194490192344928846982537 sin= 0.707106781186547524400844362 cos=-0.707106781186547524400844362 tan=-1 150 degrees, rads= 2.617993877991494365385536152 sin= 0.5 cos=-0.866025403784438646763723170 tan=-0.577350269189625764509148780 165 degrees, rads= 2.879793265790643801924089768 sin= 0.258819045102520762348898837 cos=-0.965925826289068286749743199 tan=-0.267949192431122706472553658 180 degrees, rads= 3.141592653589793238462643383 sin= 0 cos=-1 tan= 0 -1 radians, degs=-57.29577951308232087679815481 Acos= 3.141592653589793238462643383 Asin=-1.570796326794896619231321691 Atan=-0.785398163397448309615660845 -0.5 radians, degs=-28.64788975654116043839907740 Acos= 2.094395102393195492308428922 Asin=-0.523598775598298873077107230 Atan=-0.463647609000806116214256231 0 radians, degs= 0 Acos= 1.570796326794896619231321691 Asin= 0 Atan= 0 0.5 radians, degs= 28.64788975654116043839907740 Acos= 1.047197551196597746154214461 Asin= 0.523598775598298873077107230 Atan= 0.463647609000806116214256231 1.0 radians, degs= 57.29577951308232087679815481 Acos= 0 Asin= 1.570796326794896619231321691 Atan= 0.785398163397448309615660845
Ruby
Ruby's Math module contains all six functions. The functions all accept radians only, so conversion is necessary when dealing with degrees.
<lang ruby>radians = Math::PI / 4 degrees = 45.0
def deg2rad(d)
d * Math::PI / 180
end
def rad2deg(r)
r * 180 / Math::PI
end
- sine
puts "#{Math.sin(radians)} #{Math.sin(deg2rad(degrees))}"
- cosine
puts "#{Math.cos(radians)} #{Math.cos(deg2rad(degrees))}"
- tangent
puts "#{Math.tan(radians)} #{Math.tan(deg2rad(degrees))}"
- arcsine
arcsin = Math.asin(Math.sin(radians)) puts "#{arcsin} #{rad2deg(arcsin)}"
- arccosine
arccos = Math.acos(Math.cos(radians)) puts "#{arccos} #{rad2deg(arccos)}"
- arctangent
arctan = Math.atan(Math.tan(radians)) puts "#{arctan} #{rad2deg(arctan)}"</lang>
Output:
0.707106781187 0.707106781187 0.707106781187 0.707106781187 1.0 1.0 0.785398163397 45.0 0.785398163397 45.0 0.785398163397 45.0
BigDecimal
If you want more digits in the answer, then you can use the BigDecimal class. BigMath only has big versions of sine, cosine, and arctangent; so we must implement tangent, arcsine and arccosine.
<lang ruby>require 'bigdecimal' # BigDecimal require 'bigdecimal/math' # BigMath
include BigMath # Allow sin(x, prec) instead of BigMath.sin(x, prec).
- Tangent of _x_.
def tan(x, prec)
sin(x, prec) / cos(x, prec)
end
- Arcsine of _y_, domain [-1, 1], range [-pi/2, pi/2].
def asin(y, prec) # Handle angles with no tangent. return -PI / 2 if y == -1 return PI / 2 if y == 1
# Tangent of angle is y / x, where x^2 + y^2 = 1. atan(y / sqrt(1 - y * y, prec), prec) end
- Arccosine of _x_, domain [-1, 1], range [0, pi].
def acos(x, prec) # Handle angle with no tangent. return PI / 2 if x == 0
# Tangent of angle is y / x, where x^2 + y^2 = 1. a = atan(sqrt(1 - x * x, prec) / x, prec) if a < 0 a + PI(prec) else a end end
prec = 52
pi = PI(prec)
degrees = pi / 180 # one degree in radians
b1 = BigDecimal.new "1" b2 = BigDecimal.new "2" b3 = BigDecimal.new "3"
f = proc { |big| big.round(50).to_s('F') } print("Using radians:",
"\n sin(-pi / 6) = ", f[ sin(-pi / 6, prec) ], "\n cos(3 * pi / 4) = ", f[ cos(3 * pi / 4, prec) ], "\n tan(pi / 3) = ", f[ tan(pi / 3, prec) ], "\n asin(-1 / 2) = ", f[ asin(-b1 / 2, prec) ], "\n acos(-sqrt(2) / 2) = ", f[ acos(-sqrt(b2, prec) / 2, prec) ], "\n atan(sqrt(3)) = ", f[ atan(sqrt(b3, prec), prec) ], "\n")
print("Using degrees:",
"\n sin(-30) = ", f[ sin(-30 * degrees, prec) ], "\n cos(135) = ", f[ cos(135 * degrees, prec) ], "\n tan(60) = ", f[ tan(60 * degrees, prec) ], "\n asin(-1 / 2) = ", f[ asin(-b1 / 2, prec) / degrees ], "\n acos(-sqrt(2) / 2) = ", f[ acos(-sqrt(b2, prec) / 2, prec) / degrees ], "\n atan(sqrt(3)) = ", f[ atan(sqrt(b3, prec), prec) / degrees ], "\n")</lang>
Output:
Using radians: sin(-pi / 6) = -0.5 cos(3 * pi / 4) = -0.70710678118654752440084436210484903928483593768847 tan(pi / 3) = 1.73205080756887729352744634150587236694280525381038 asin(-1 / 2) = -0.52359877559829887307710723054658381403286156656252 acos(-sqrt(2) / 2) = 2.35619449019234492884698253745962716314787704953133 atan(sqrt(3)) = 1.04719755119659774615421446109316762806572313312504 Using degrees: sin(-30) = -0.5 cos(135) = -0.70710678118654752440084436210484903928483593768847 tan(60) = 1.73205080756887729352744634150587236694280525381038 asin(-1 / 2) = -30.0 acos(-sqrt(2) / 2) = 135.0 atan(sqrt(3)) = 60.0
Run BASIC
<lang Runbasic>pi = 22/7 tab$ = chr$(9) radians = pi / 4 'a.k.a. 45 degrees degrees = 45 * pi / 180 'convert 45 degrees to radians
PRINT " Sine: ";SIN(radians) ;tab$; SIN(degrees) 'sine PRINT " Cosine: ";COS(radians) ;tab$; COS(degrees) 'cosine PRINT "Tnagent: ";TAN(radians) ;tab$; TAN(degrees) 'tangent print " Arcsin: ";ASN(radians) ;tab$; ASN(degrees) 'arcsin print " Arccos: ";ACS(radians) ;tab$; ACS(degrees) 'arcsin print " Arctan: ";ATN(radians) ;tab$; ATN(degrees) 'arcsin print " TanAtn: ";ATN(TAN(radians));tab$;ATN(TAN(radians)) * 180 / pi 'tanatn </lang>
SAS
<lang sas>data _null_; pi = 4*atan(1); deg = 30; rad = pi/6; k = pi/180; x = 0.2;
a = sin(rad); b = sin(deg*k); put a b;
a = cos(rad); b = cos(deg*k); put a b;
a = tan(rad); b = tan(deg*k); put a b;
a=arsin(x); b=arsin(x)/k; put a b;
a=arcos(x); b=arcos(x)/k; put a b;
a=atan(x); b=atan(x)/k; put a b; run;</lang>
Scheme
<lang scheme>(define pi (* 4 (atan 1)))
(define radians (/ pi 4)) (define degrees 45)
(display (sin radians)) (display " ") (display (sin (* degrees (/ pi 180)))) (newline)
(display (cos radians)) (display " ") (display (cos (* degrees (/ pi 180)))) (newline)
(display (tan radians)) (display " ") (display (tan (* degrees (/ pi 180)))) (newline)
(define arcsin (asin (sin radians))) (display arcsin) (display " ") (display (* arcsin (/ 180 pi))) (newline)
(define arccos (acos (cos radians))) (display arccos) (display " ") (display (* arccos (/ 180 pi))) (newline)
(define arctan (atan (tan radians))) (display arctan) (display " ") (display (* arctan (/ 180 pi))) (newline)</lang>
Seed7
The example below uses the libaray math.s7i, which defines, besides many other functions, sin, cos, tan, asin, acos and atan.
<lang seed7>$ include "seed7_05.s7i";
include "float.s7i"; include "math.s7i";
const proc: main is func
local const float: radians is PI / 4.0; const float: degrees is 45.0; begin writeln(" radians degrees"); writeln("sine: " <& sin(radians) digits 5 <& sin(degrees * PI / 180.0) digits 5 lpad 9); writeln("cosine: " <& cos(radians) digits 5 <& cos(degrees * PI / 180.0) digits 5 lpad 9); writeln("tangent: " <& tan(radians) digits 5 <& tan(degrees * PI / 180.0) digits 5 lpad 9); writeln("arcsine: " <& asin(0.70710677) digits 5 <& asin(0.70710677) * 180.0 / PI digits 5 lpad 9); writeln("arccosine: " <& acos(0.70710677) digits 5 <& acos(0.70710677) * 180.0 / PI digits 5 lpad 9); writeln("arctangent: " <& atan(1.0) digits 5 <& atan(1.0) * 180.0 / PI digits 5 lpad 9); end func;</lang>
Output:
radians degrees sine: 0.70711 0.70711 cosine: 0.70711 0.70711 tangent: 1.00000 1.00000 arcsine: 0.78540 45.00000 arccosine: 0.78540 45.00000 arctangent: 0.78540 45.00000
Tcl
The built-in functions only take radian arguments. <lang tcl>package require Tcl 8.5
proc PI {} {expr {4*atan(1)}} proc deg2rad d {expr {$d/180*[PI]}} proc rad2deg r {expr {$r*180/[PI]}}
namespace path ::tcl::mathfunc
proc trig degrees {
set radians [deg2rad $degrees] puts [sin $radians] puts [cos $radians] puts [tan $radians] set arcsin [asin [sin $radians]]; puts "$arcsin [rad2deg $arcsin]" set arccos [acos [cos $radians]]; puts "$arccos [rad2deg $arccos]" set arctan [atan [tan $radians]]; puts "$arctan [rad2deg $arctan]"
} trig 60.0</lang>
0.8660254037844386 0.5000000000000001 1.7320508075688767 1.0471975511965976 59.99999999999999 1.0471975511965976 59.99999999999999 1.0471975511965976 59.99999999999999
XPL0
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations def Pi = 3.14159265358979323846;
func real ATan(Y); \Arc tangent real Y; return ATan2(Y, 1.0);
func real Deg(X); \Convert radians to degrees real X; return 57.2957795130823 * X;
func real Rad(X); \Convert degrees to radians real X; return X / 57.2957795130823;
real A, B, C; [A:= Sin(Pi/6.0); RlOut(0, A); ChOut(0, 9\tab\); RlOut(0, Sin(Rad(30.0))); CrLf(0); B:= Cos(Pi/6.0); RlOut(0, B); ChOut(0, 9\tab\); RlOut(0, Cos(Rad(30.0))); CrLf(0); C:= Tan(Pi/4.0); RlOut(0, C); ChOut(0, 9\tab\); RlOut(0, Tan(Rad(45.0))); CrLf(0);
RlOut(0, ASin(A)); ChOut(0, 9\tab\); RlOut(0, Deg(ASin(A))); CrLf(0); RlOut(0, ACos(B)); ChOut(0, 9\tab\); RlOut(0, Deg(ACos(B))); CrLf(0); RlOut(0, ATan(C)); ChOut(0, 9\tab\); RlOut(0, Deg(ATan(C))); CrLf(0); ]</lang>
Output:
0.50000 0.50000 0.86603 0.86603 1.00000 1.00000 0.52360 30.00000 0.52360 30.00000 0.78540 45.00000
- Programming Tasks
- Arithmetic operations
- GAP/Omit
- ACL2
- ACL2 examples needing attention
- Examples needing attention
- ActionScript
- Ada
- ALGOL 68
- AutoHotkey
- AWK
- BASIC
- BBC BASIC
- Bc
- Bc -l
- C
- C++
- C sharp
- Clojure
- Common Lisp
- D
- E
- Erlang
- Fantom
- Forth
- Fortran
- Go
- Groovy
- Haskell
- HicEst
- IDL
- Icon
- Unicon
- J
- Java
- JavaScript
- Liberty BASIC
- Logo
- Lua
- Mathematica
- MATLAB
- MAXScript
- Metafont
- OCaml
- Octave
- Oz
- PARI/GP
- Pascal
- Math
- Perl
- Perl 6
- PL/I
- PL/SQL
- PHP
- PicoLisp
- Pop11
- PostScript
- PowerShell
- PureBasic
- Python
- R
- REBOL
- REXX
- Ruby
- Run BASIC
- SAS
- Scheme
- Seed7
- Tcl
- XPL0
- Batch File/Omit
- M4/Omit
- Mathematics