Trigonometric functions: Difference between revisions
m (→{{header|COBOL}}: Corrected mistake.) |
(Added Easylang) |
||
(129 intermediate revisions by 60 users not shown) | |||
Line 1: | Line 1: | ||
{{task|Arithmetic operations}} |
{{task|Arithmetic operations}} |
||
[[Category:Mathematics]] |
|||
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 [[wp:List of trigonometric identities|known approximation or identity]]. |
|||
;Task: |
|||
If your language has a library or built-in functions for trigonometry, show examples of: |
|||
::* sine |
|||
::* cosine |
|||
::* tangent |
|||
::* inverses (of the above) |
|||
<br>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 [[wp:List of trigonometric identities|known approximation or identity]]. |
|||
<br><br> |
|||
=={{header|11l}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="11l">V rad = math:pi / 4 |
|||
V deg = 45.0 |
|||
print(‘Sine: ’sin(rad)‘ ’sin(radians(deg))) |
|||
print(‘Cosine: ’cos(rad)‘ ’cos(radians(deg))) |
|||
print(‘Tangent: ’tan(rad)‘ ’tan(radians(deg))) |
|||
V arcsine = asin(sin(rad)) |
|||
print(‘Arcsine: ’arcsine‘ ’degrees(arcsine)) |
|||
V arccosine = acos(cos(rad)) |
|||
print(‘Arccosine: ’arccosine‘ ’degrees(arccosine)) |
|||
V arctangent = atan(tan(rad)) |
|||
print(‘Arctangent: ’arctangent‘ ’degrees(arctangent))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sine: 0.707106781 0.707106781 |
|||
Cosine: 0.707106781 0.707106781 |
|||
Tangent: 1 1 |
|||
Arcsine: 0.785398163 45 |
|||
Arccosine: 0.785398163 45 |
|||
Arctangent: 0.785398163 45 |
|||
</pre> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
Line 6: | Line 46: | ||
(This doesn't have the inverse functions; the Taylor series for those take too long to converge.) |
(This doesn't have the inverse functions; the Taylor series for those take too long to converge.) |
||
< |
<syntaxhighlight lang="lisp">(defun fac (n) |
||
(if (zp n) |
(if (zp n) |
||
1 |
1 |
||
Line 84: | Line 124: | ||
(cw "~%tangent of pi / 4 radians: ") |
(cw "~%tangent of pi / 4 radians: ") |
||
(cw (as-decimal-str (tangent (/ *pi-approx* 4)) 20)) |
(cw (as-decimal-str (tangent (/ *pi-approx* 4)) 20)) |
||
(cw "~%")))</ |
(cw "~%")))</syntaxhighlight> |
||
<pre>sine of pi / 4 radians: 0.70710678118654752440 |
<pre>sine of pi / 4 radians: 0.70710678118654752440 |
||
Line 93: | Line 133: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
Actionscript supports basic trigonometric and inverse trigonometric functions via the Math class, including the atan2 function, but not the hyperbolic functions. |
Actionscript supports basic trigonometric and inverse trigonometric functions via the Math class, including the atan2 function, but not the hyperbolic functions. |
||
< |
<syntaxhighlight lang="actionscript">trace("Radians:"); |
||
trace("sin(Pi/4) = ", Math.sin(Math.PI/4)); |
trace("sin(Pi/4) = ", Math.sin(Math.PI/4)); |
||
trace("cos(Pi/4) = ", Math.cos(Math.PI/4)); |
trace("cos(Pi/4) = ", Math.cos(Math.PI/4)); |
||
Line 109: | Line 149: | ||
trace("arctan(0.5) = ", Math.atan(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); |
trace("arctan2(-1,-2) = ", Math.atan2(-1,-2)*180/Math.PI); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Ada provides library trig functions which default to radians along with corresponding library functions for which the cycle can be specified. |
Ada provides library trig functions which default to radians along with corresponding library functions for which the cycle can be specified. <br> |
||
The examples below specify the cycle for degrees and for radians. <br> |
|||
<lang ada>with Ada.Numerics.Elementary_Functions; |
|||
The output of the inverse trig functions is in units of the specified cycle (degrees or radians). |
|||
<syntaxhighlight lang="ada">with Ada.Numerics.Elementary_Functions; |
|||
use Ada.Numerics.Elementary_Functions; |
use Ada.Numerics.Elementary_Functions; |
||
with Ada.Float_Text_Io; use Ada.Float_Text_Io; |
with Ada.Float_Text_Io; use Ada.Float_Text_Io; |
||
Line 146: | Line 189: | ||
Put (Arccot (X => Cot (Angle_Degrees, Degrees_Cycle)), |
Put (Arccot (X => Cot (Angle_Degrees, Degrees_Cycle)), |
||
Arccot (X => Cot (Angle_Degrees, Degrees_Cycle))); |
Arccot (X => Cot (Angle_Degrees, Degrees_Cycle))); |
||
end Trig;</ |
end Trig;</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
0.70711 0.70711 |
0.70711 0.70711 |
||
Line 159: | Line 202: | ||
45.00000 0.78540 |
45.00000 0.78540 |
||
</pre> |
</pre> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{trans|C}} |
{{trans|C}} |
||
Line 167: | Line 211: | ||
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}} |
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}} |
||
< |
<syntaxhighlight lang="algol68">main:( |
||
REAL pi = 4 * arc tan(1); |
REAL pi = 4 * arc tan(1); |
||
# Pi / 4 is 45 degrees. All answers should be the same. # |
# Pi / 4 is 45 degrees. All answers should be the same. # |
||
Line 188: | Line 232: | ||
temp := arc tan(tan(radians)); |
temp := arc tan(tan(radians)); |
||
print((temp, " ", temp * 180 / pi, new line)) |
print((temp, " ", temp * 180 / pi, new line)) |
||
)</ |
)</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
+.707106781186548e +0 +.707106781186548e +0 |
+.707106781186548e +0 +.707106781186548e +0 |
||
Line 198: | Line 242: | ||
+.785398163397448e +0 +.450000000000000e +2 |
+.785398163397448e +0 +.450000000000000e +2 |
||
</pre> |
</pre> |
||
=={{header|ALGOL W}}== |
|||
<syntaxhighlight lang="algolw">begin |
|||
% Algol W only supplies sin, cos and arctan as standard. We can define % |
|||
% arcsin, arccos and tan functions using these. The standard functions % |
|||
% use radians so we also provide versions that use degrees % |
|||
% convert degrees to radians % |
|||
real procedure toRadians( real value x ) ; pi * ( x / 180 ); |
|||
% convert radians to degrees % |
|||
real procedure toDegrees( real value x ) ; 180 * ( x / pi ); |
|||
% tan of an angle in radians % |
|||
real procedure tan( real value x ) ; sin( x ) / cos( x ); |
|||
% arcsin in radians % |
|||
real procedure arcsin( real value x ) ; arctan( x / sqrt( 1 - ( x * x ) ) ); |
|||
% arccos in radians % |
|||
real procedure arccos( real value x ) ; arctan( sqrt( 1 - ( x * x ) ) / x ); |
|||
% sin of an angle in degrees % |
|||
real procedure sinD( real value x ) ; sin( toRadians( x ) ); |
|||
% cos of an angle in degrees % |
|||
real procedure cosD( real value x ) ; cos( toRadians( x ) ); |
|||
% tan of an angle in degrees % |
|||
real procedure tanD( real value x ) ; tan( toRadians( x ) ); |
|||
% arctan in degrees % |
|||
real procedure arctanD( real value x ) ; toDegrees( arctan( x ) ); |
|||
% arcsin in degrees % |
|||
real procedure arcsinD( real value x ) ; toDegrees( arcsin( x ) ); |
|||
% arccos in degrees % |
|||
real procedure arccosD( real value x ) ; toDegrees( arccos( x ) ); |
|||
% test the procedures % |
|||
begin |
|||
real piOver4, piOver3, oneOverRoot2, root3Over2; |
|||
piOver3 := pi / 3; piOver4 := pi / 4; |
|||
oneOverRoot2 := 1.0 / sqrt( 2 ); root3Over2 := sqrt( 3 ) / 2; |
|||
r_w := 12; r_d := 5; r_format := "A"; s_w := 0; % set output format % |
|||
write( "PI/4: ", piOver4, " 1/root(2): ", oneOverRoot2 ); |
|||
write(); |
|||
write( "sin 45 degrees: ", sinD( 45 ), " sin pi/4 radians: ", sin( piOver4 ) ); |
|||
write( "cos 45 degrees: ", cosD( 45 ), " cos pi/4 radians: ", cos( piOver4 ) ); |
|||
write( "tan 45 degrees: ", tanD( 45 ), " tan pi/4 radians: ", tan( piOver4 ) ); |
|||
write(); |
|||
write( "arcsin( sin( pi/4 radians ) ): ", arcsin( sin( piOver4 ) ) ); |
|||
write( "arccos( cos( pi/4 radians ) ): ", arccos( cos( piOver4 ) ) ); |
|||
write( "arctan( tan( pi/4 radians ) ): ", arctan( tan( piOver4 ) ) ); |
|||
write(); |
|||
write( "PI/3: ", piOver4, " root(3)/2: ", root3Over2 ); |
|||
write(); |
|||
write( "sin 60 degrees: ", sinD( 60 ), " sin pi/3 radians: ", sin( piOver3 ) ); |
|||
write( "cos 60 degrees: ", cosD( 60 ), " cos pi/3 radians: ", cos( piOver3 ) ); |
|||
write( "tan 60 degrees: ", tanD( 60 ), " tan pi/3 radians: ", tan( piOver3 ) ); |
|||
write(); |
|||
write( "arcsin( sin( 60 degrees ) ): ", arcsinD( sinD( 60 ) ) ); |
|||
write( "arccos( cos( 60 degrees ) ): ", arccosD( cosD( 60 ) ) ); |
|||
write( "arctan( tan( 60 degrees ) ): ", arctanD( tanD( 60 ) ) ); |
|||
end |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
PI/4: 0.78539 1/root(2): 0.70710 |
|||
sin 45 degrees: 0.70710 sin pi/4 radians: 0.70710 |
|||
cos 45 degrees: 0.70710 cos pi/4 radians: 0.70710 |
|||
tan 45 degrees: 1.00000 tan pi/4 radians: 1.00000 |
|||
arcsin( sin( pi/4 radians ) ): 0.78539 |
|||
arccos( cos( pi/4 radians ) ): 0.78539 |
|||
arctan( tan( pi/4 radians ) ): 0.78539 |
|||
PI/3: 0.78539 root(3)/2: 0.86602 |
|||
sin 60 degrees: 0.86602 sin pi/3 radians: 0.86602 |
|||
cos 60 degrees: 0.50000 cos pi/3 radians: 0.50000 |
|||
tan 60 degrees: 1.73205 tan pi/3 radians: 1.73205 |
|||
arcsin( sin( 60 degrees ) ): 60.00000 |
|||
arccos( cos( 60 degrees ) ): 60.00000 |
|||
arctan( tan( 60 degrees ) ): 60.00000 |
|||
</pre> |
|||
=={{header|Arturo}}== |
|||
{{trans|C}} |
|||
<syntaxhighlight lang="rebol">pi: 4*atan 1.0 |
|||
radians: pi/4 |
|||
degrees: 45.0 |
|||
print "sine" |
|||
print [sin radians, sin degrees*pi/180] |
|||
print "cosine" |
|||
print [cos radians, cos degrees*pi/180] |
|||
print "tangent" |
|||
print [tan radians, tan degrees*pi/180] |
|||
print "arcsine" |
|||
print [asin sin radians, (asin sin radians)*180/pi] |
|||
print "arccosine" |
|||
print [acos cos radians, (acos cos radians)*180/pi] |
|||
print "arctangent" |
|||
print [atan tan radians, (atan tan radians)*180/pi]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>sine |
|||
0.7071067811865475 0.7071067811865475 |
|||
cosine |
|||
0.7071067811865476 0.7071067811865476 |
|||
tangent |
|||
0.9999999999999999 0.9999999999999999 |
|||
arcsine |
|||
0.7853981633974482 44.99999999999999 |
|||
arccosine |
|||
0.7853981633974483 45.0 |
|||
arctangent |
|||
0.7853981633974483 45.0</pre> |
|||
=={{header|Asymptote}}== |
|||
<syntaxhighlight lang="asymptote">real pi = 4 * atan(1); |
|||
real radian = pi / 4.0; |
|||
real angulo = 45.0 * pi / 180; |
|||
write("Radians : ", radian); |
|||
write("Degrees : ", angulo / pi * 180); |
|||
write(); |
|||
write("Sine : ", sin(radian), sin(angulo)); |
|||
write("Cosine : ", cos(radian), cos(angulo)); |
|||
write("Tangent : ", tan(radian), tan(angulo)); |
|||
write(); |
|||
real temp = asin(sin(radian)); |
|||
write("Arc Sine : ", temp, temp * 180 / pi); |
|||
temp = acos(cos(radian)); |
|||
write("Arc Cosine : ", temp, temp * 180 / pi); |
|||
temp = atan(tan(radian)); |
|||
write("Arc Tangent : ", temp, temp * 180 / pi);</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Radians : 0.785398163397448 |
|||
Degrees : 45 |
|||
Sine : 0.707106781186547 0.707106781186547 |
|||
Cosine : 0.707106781186548 0.707106781186548 |
|||
Tangent : 1 1 |
|||
Arc Sine : 0.785398163397448 45 |
|||
Arc Cosine : 0.785398163397448 45 |
|||
Arc Tangent : 0.785398163397448 45</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="autohotkey">pi := 4 * atan(1) |
||
radians := pi / 4 |
radians := pi / 4 |
||
degrees := 45.0 |
degrees := 45.0 |
||
Line 228: | Line 431: | ||
0.785398 45.000000 |
0.785398 45.000000 |
||
0.785398 45.000000 |
0.785398 45.000000 |
||
*/</ |
*/</syntaxhighlight> |
||
=={{header|Autolisp}}== |
|||
Autolisp provides <b>(sin x) (cos x) (tan x)</b> and <b>(atan x)</b>. |
|||
Function arguments are expressed in radians. |
|||
<syntaxhighlight lang="autolisp"> |
|||
(defun rad_to_deg (rad)(* 180.0 (/ rad PI))) |
|||
(defun deg_to_rad (deg)(* PI (/ deg 180.0))) |
|||
(defun asin (x) |
|||
(cond |
|||
((and(> x -1.0)(< x 1.0)) (atan (/ x (sqrt (- 1.0 (* x x)))))) |
|||
((= x -1.0) (* -1.0 (/ pi 2))) |
|||
((= x 1) (/ pi 2)) |
|||
) |
|||
) |
|||
(defun acos (x) |
|||
(cond |
|||
((and(>= x -1.0)(<= x 1.0)) (-(* pi 0.5) (asin x))) |
|||
) |
|||
) |
|||
(list |
|||
(list "cos PI/6" (cos (/ pi 6)) "cos 30 deg" (cos (deg_to_rad 30))) |
|||
(list "sin PI/4" (sin (/ pi 4)) "sin 45 deg" (sin (deg_to_rad 45))) |
|||
(list "tan PI/3" (tan (/ pi 3))"tan 60 deg" (tan (deg_to_rad 60))) |
|||
(list "asin 1 rad" (asin 1.0) "asin 1 rad (deg)" (rad_to_deg (asin 1.0))) |
|||
(list "acos 1/2 rad" (acos (/ 1 2.0)) "acos 1/2 rad (deg)" (rad_to_deg (acos (/ 1 2.0)))) |
|||
(list "atan pi/12" (atan (/ pi 12)) "atan 15 deg" (rad_to_deg(atan(deg_to_rad 15)))) |
|||
) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
(("cos PI/6 rad" 0.866025 "cos 30 deg" 0.866025) |
|||
("sin PI/4 rad" 0.707107 "sin 45 deg" 0.707107) |
|||
("tan PI/3 rad" 1.73205 " tan 60 deg" 1.73205) |
|||
("asin 1 rad" 1.57080 "asin 1 rad (deg)" 90.0000) |
|||
("acos 1/2 rad" 1.04720 "acos 1/2 rad" 60.0000) |
|||
("atan pi/12 rad" 0.256053 "atan 15 deg" 14.6707)) |
|||
</pre> |
|||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Line 247: | Line 490: | ||
<tt>atan2(y, x)</tt> 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 ''x<sup>2</sup> + y<sup>2</sup> = 1''. To calculate arcsine in the range ''[-pi/2, pi/2]'', we take the angle of points on the half-circle ''x = sqrt(1 - y<sup>2</sup>)''. To calculate arccosine in the range ''[0, pi]'', we take the angle of points on the half-circle ''y = sqrt(1 - x<sup>2</sup>)''. |
<tt>atan2(y, x)</tt> 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 ''x<sup>2</sup> + y<sup>2</sup> = 1''. To calculate arcsine in the range ''[-pi/2, pi/2]'', we take the angle of points on the half-circle ''x = sqrt(1 - y<sup>2</sup>)''. To calculate arccosine in the range ''[0, pi]'', we take the angle of points on the half-circle ''y = sqrt(1 - x<sup>2</sup>)''. |
||
< |
<syntaxhighlight lang="awk"># tan(x) = tangent of x |
||
function tan(x) { |
function tan(x) { |
||
return sin(x) / cos(x) |
return sin(x) / cos(x) |
||
Line 286: | Line 529: | ||
print " acos(-sqrt(2) / 2) =", acos(-sqrt(2) / 2) / degrees |
print " acos(-sqrt(2) / 2) =", acos(-sqrt(2) / 2) / degrees |
||
print " atan(sqrt(3)) =", atan(sqrt(3)) / degrees |
print " atan(sqrt(3)) =", atan(sqrt(3)) / degrees |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
|||
Output: <pre>Using radians: |
|||
<pre>Using radians: |
|||
sin(-pi / 6) = -0.5 |
sin(-pi / 6) = -0.5 |
||
cos(3 * pi / 4) = -0.707107 |
cos(3 * pi / 4) = -0.707107 |
||
Line 302: | Line 546: | ||
acos(-sqrt(2) / 2) = 135 |
acos(-sqrt(2) / 2) = 135 |
||
atan(sqrt(3)) = 60</pre> |
atan(sqrt(3)) = 60</pre> |
||
=={{header|Axe}}== |
|||
Axe implements sine, cosine, and inverse tangent natively. One period is [0, 256) and the results are [-127, 127] for maximum precision. |
|||
The inverse tangent takes dX and dY parameters, rather than a single argument. This is because it is most often used to calculate angles. |
|||
<syntaxhighlight lang="axe">Disp sin(43)▶Dec,i |
|||
Disp cos(43)▶Dec,i |
|||
Disp tan⁻¹(10,10)▶Dec,i</syntaxhighlight> |
|||
{{out}} |
|||
<pre> 113 |
|||
68 |
|||
32</pre> |
|||
Below is the worked out math. |
|||
On a period of 256, an argument of 43 is equivalent to <math>\frac{\pi}{3} * \frac{128}{\pi}</math>. |
|||
Furthermore, <math>127*\frac{\sqrt{3}}{2} \approx 111</math> and <math>127*\frac{1}{2} \approx 64</math>. |
|||
So <math>\sin{43} \approx 113</math> and <math>\cos{43} \approx 68</math>. Axe uses approximations to calculate the trigonometric functions. |
|||
dX and dY values of 10 mean that the angle between them should be <math>\frac{\pi}{4}</math>. Indeed, the result <math>\tan^{-1}{(10, 10)} = 32 = \frac{128}{4}</math>. |
|||
=={{header|BaCon}}== |
|||
<syntaxhighlight lang="qbasic">' Trigonometric functions in BaCon use Radians for input values |
|||
' The RAD() function converts from degrees to radians |
|||
FOR v$ IN "0, 10, 45, 90, 190.5" |
|||
d = VAL(v$) * 1.0 |
|||
r = RAD(d) * 1.0 |
|||
PRINT "Sine: ", d, " degrees (or ", r, " radians) is ", SIN(r) |
|||
PRINT "Cosine: ", d, " degrees (or ", r, " radians) is ", COS(r) |
|||
PRINT "Tangent: ", d, " degrees (or ", r, " radians) is ", TAN(r) |
|||
PRINT |
|||
PRINT "Arc Sine: ", SIN(r), " is ", DEG(ASIN(SIN(r))), " degrees (or ", ASIN(SIN(r)), " radians)" |
|||
PRINT "Arc CoSine: ", COS(r), " is ", DEG(ACOS(COS(r))), " degrees (or ", ACOS(COS(r)), " radians)" |
|||
PRINT "Arc Tangent: ", TAN(r), " is ", DEG(ATN(TAN(r))), " degrees (or ", ATN(TAN(r)), " radians)" |
|||
PRINT |
|||
NEXT</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ bacon -q trigonometric-functions.bac |
|||
... |
|||
Done, program 'trigonometric-functions' ready. |
|||
prompt$ ./trigonometric-functions |
|||
Sine: 0 degrees (or 0 radians) is 0 |
|||
Cosine: 0 degrees (or 0 radians) is 1 |
|||
Tangent: 0 degrees (or 0 radians) is 0 |
|||
Arc Sine: 0 is 0 degrees (or 0 radians) |
|||
Arc CoSine: 1 is 0 degrees (or 0 radians) |
|||
Arc Tangent: 0 is 0 degrees (or 0 radians) |
|||
Sine: 10 degrees (or 0.174533 radians) is 0.173648 |
|||
Cosine: 10 degrees (or 0.174533 radians) is 0.984808 |
|||
Tangent: 10 degrees (or 0.174533 radians) is 0.176327 |
|||
Arc Sine: 0.173648 is 10 degrees (or 0.174533 radians) |
|||
Arc CoSine: 0.984808 is 10 degrees (or 0.174533 radians) |
|||
Arc Tangent: 0.176327 is 10 degrees (or 0.174533 radians) |
|||
Sine: 45 degrees (or 0.785398 radians) is 0.707107 |
|||
Cosine: 45 degrees (or 0.785398 radians) is 0.707107 |
|||
Tangent: 45 degrees (or 0.785398 radians) is 1 |
|||
Arc Sine: 0.707107 is 45 degrees (or 0.785398 radians) |
|||
Arc CoSine: 0.707107 is 45 degrees (or 0.785398 radians) |
|||
Arc Tangent: 1 is 45 degrees (or 0.785398 radians) |
|||
Sine: 90 degrees (or 1.5708 radians) is 1 |
|||
Cosine: 90 degrees (or 1.5708 radians) is 6.12323e-17 |
|||
Tangent: 90 degrees (or 1.5708 radians) is 16331239353195370 |
|||
Arc Sine: 1 is 90 degrees (or 1.5708 radians) |
|||
Arc CoSine: 6.12323e-17 is 90 degrees (or 1.5708 radians) |
|||
Arc Tangent: 16331239353195370 is 90 degrees (or 1.5708 radians) |
|||
Sine: 190.5 degrees (or 3.32485 radians) is -0.182236 |
|||
Cosine: 190.5 degrees (or 3.32485 radians) is -0.983255 |
|||
Tangent: 190.5 degrees (or 3.32485 radians) is 0.185339 |
|||
Arc Sine: -0.182236 is -10.5 degrees (or -0.18326 radians) |
|||
Arc CoSine: -0.983255 is 169.5 degrees (or 2.95833 radians) |
|||
Arc Tangent: 0.185339 is 10.5 degrees (or 0.18326 radians)</pre> |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
{{works with|QuickBasic|4.5}} |
{{works with|QuickBasic|4.5}} |
||
QuickBasic 4.5 does not have arcsin and arccos built in. They are defined by identities found [[wp:Arctan#Relationships_among_the_inverse_trigonometric_functions|here]]. |
QuickBasic 4.5 does not have arcsin and arccos built in. They are defined by identities found [[wp:Arctan#Relationships_among_the_inverse_trigonometric_functions|here]]. |
||
< |
<syntaxhighlight lang="qbasic">pi = 3.141592653589793# |
||
radians = pi / 4 'a.k.a. 45 degrees |
radians = pi / 4 'a.k.a. 45 degrees |
||
degrees = 45 * pi / 180 'convert 45 degrees to radians once |
degrees = 45 * pi / 180 'convert 45 degrees to radians once |
||
Line 320: | Line 652: | ||
arccos = 2 * ATN(SQR(1 - thecos ^ 2) / (1 + thecos)) |
arccos = 2 * ATN(SQR(1 - thecos ^ 2) / (1 + thecos)) |
||
PRINT arccos + " " + arccos * 180 / pi |
PRINT arccos + " " + arccos * 180 / pi |
||
PRINT ATN(TAN(radians)) + " " + ATN(TAN(radians)) * 180 / pi 'arctan</ |
PRINT ATN(TAN(radians)) + " " + ATN(TAN(radians)) * 180 / pi 'arctan</syntaxhighlight> |
||
==={{header|Applesoft BASIC}}=== |
|||
The arcsine and arccoscine functions, while not intrinsic to Applesoft BASIC, are |
|||
calculated using the existing BASIC functions and implemented as FN ASN and FN ACS |
|||
using the DEF FN function. |
|||
<syntaxhighlight lang="gwbasic"> 100 TAU = 8 * ATN (1) |
|||
110 RAD = TAU / 8 |
|||
120 DEG = 45.0 |
|||
130 DEF FN RAD(DEG) = DEG * TAU / 360 |
|||
140 DEF FN DEG(RAD) = RAD / TAU * 360 |
|||
150 DEF FN ASN(RAD) = ATN (RAD / SQR ( - RAD * RAD + 1)) |
|||
160 DEF FN ACS(RAD) = - ATN (RAD / SQR ( - RAD * RAD + 1)) + TAU / 4 |
|||
170 PRINT " SINE: " SIN (RAD);: HTAB (25): PRINT SIN ( FN RAD(DEG)) |
|||
180 PRINT " COSINE: " COS (RAD);: HTAB (25): PRINT COS ( FN RAD(DEG)) |
|||
190 PRINT " TANGENT: " TAN (RAD);: HTAB (25): PRINT TAN ( FN RAD(DEG)) |
|||
200 ARC = FN ASN( SIN (RAD)) |
|||
210 PRINT " ARCSINE: "ARC;: HTAB (25): PRINT FN DEG(ARC) |
|||
220 ARC = FN ACS( COS (RAD)) |
|||
230 PRINT " ARCCOSINE: "ARC;: HTAB (25): PRINT FN DEG(ARC) |
|||
240 ARC = ATN ( TAN (RAD)) |
|||
250 PRINT " ARCTANGENT: "ARC;: HTAB (25): PRINT FN DEG(ARC);</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
SINE: .707106781 .707106781 |
|||
COSINE: .707106781 .707106781 |
|||
TANGENT: 1 1 |
|||
ARCSINE: .785398163 45 |
|||
ARCCOSINE: .785398164 45.0000001 |
|||
ARCTANGENT: .785398163 45 |
|||
</pre> |
|||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="basic256">radian = pi / 4 |
|||
angulo = 45.0 * pi / 180 |
|||
print "Radians : "; radians(angulo); " "; |
|||
print "Degrees : "; degrees(radian) |
|||
print |
|||
print "Sine : "; sin(radian); " "; sin(angulo) |
|||
print "Cosine : "; cos(radian); " "; cos(angulo) |
|||
print "Tangent : "; tan(radian); " "; tan(angulo) |
|||
print |
|||
#temp = asin(sin(radians(angulo))) |
|||
temp = asin(sin(radian)) |
|||
print "Arc Sine : "; temp; " "; degrees(temp) |
|||
temp = acos(cos(radian)) |
|||
print "Arc Cosine : "; temp; " "; degrees(temp) |
|||
temp = atan(tan(radian)) |
|||
print "Arc Tangent : "; temp; " "; degrees(temp) |
|||
end</syntaxhighlight> |
|||
=={{header|BBC BASIC}}== |
==={{header|BBC BASIC}}=== |
||
< |
<syntaxhighlight lang="bbcbasic"> @% = &90F : REM set column width |
||
angle_radians = PI/5 |
angle_radians = PI/5 |
||
Line 336: | Line 717: | ||
PRINT ASN(number), DEG(ASN(number)) |
PRINT ASN(number), DEG(ASN(number)) |
||
PRINT ACS(number), DEG(ACS(number)) |
PRINT ACS(number), DEG(ACS(number)) |
||
PRINT ATN(number), DEG(ATN(number))</ |
PRINT ATN(number), DEG(ATN(number))</syntaxhighlight> |
||
==={{header|IS-BASIC}}=== |
|||
<syntaxhighlight lang="is-basic">100 LET DG=DEG(PI/4) |
|||
110 OPTION ANGLE DEGREES |
|||
120 PRINT SIN(DG) |
|||
130 PRINT COS(DG) |
|||
140 PRINT TAN(DG) |
|||
150 PRINT ASIN(SIN(DG)) |
|||
160 PRINT ACOS(COS(DG)) |
|||
170 PRINT ATN(TAN(DG)) |
|||
180 LET RD=RAD(45) |
|||
190 OPTION ANGLE RADIANS |
|||
200 PRINT SIN(RD) |
|||
210 PRINT COS(RD) |
|||
220 PRINT TAN(RD) |
|||
230 PRINT ASIN(SIN(RD)) |
|||
240 PRINT ACOS(COS(RD)) |
|||
250 PRINT ATN(TAN(RD))</syntaxhighlight> |
|||
==={{header|Yabasic}}=== |
|||
<syntaxhighlight lang="yabasic">radians = pi / 4 |
|||
degrees = 45.0 * pi / 180 |
|||
tab$ = chr$(09) |
|||
print "Radians : ", radians, " ", |
|||
print "Degrees : ", degrees / pi * 180 |
|||
print |
|||
print "Sine : ", sin(radians), tab$, sin(degrees) |
|||
print "Cosine : ", cos(radians), tab$, cos(degrees) |
|||
print "Tangent : ", tan(radians), tab$, tan(degrees) |
|||
print |
|||
temp = asin(sin(radians)) |
|||
print "Arc Sine : ", temp, tab$, temp * 180 / pi |
|||
temp = acos(cos(radians)) |
|||
print "Arc Cosine : ", temp, tab$, temp * 180 / pi |
|||
temp = atan(tan(radians)) |
|||
print "Arc Tangent : ", temp, tab$, temp * 180 / pi |
|||
end</syntaxhighlight> |
|||
=={{header|bc}}== |
=={{header|bc}}== |
||
{{libheader|bc -l}} |
{{libheader|bc -l}} |
||
{{trans|AWK}} |
{{trans|AWK}} |
||
< |
<syntaxhighlight lang="bc">/* t(x) = tangent of x */ |
||
define t(x) { |
define t(x) { |
||
return s(x) / c(x) |
return s(x) / c(x) |
||
Line 395: | Line 814: | ||
" atan(sqrt(3)) = "; a(sqrt(3)) / d |
" atan(sqrt(3)) = "; a(sqrt(3)) / d |
||
quit</ |
quit</syntaxhighlight> |
||
{{out}} |
|||
Output: <pre>Using radians: |
|||
<pre>Using radians: |
|||
sin(-pi / 6) = -.49999999999999999999999999999999999999999999999999 |
sin(-pi / 6) = -.49999999999999999999999999999999999999999999999999 |
||
cos(3 * pi / 4) = -.70710678118654752440084436210484903928483593768845 |
cos(3 * pi / 4) = -.70710678118654752440084436210484903928483593768845 |
||
Line 411: | Line 831: | ||
acos(-sqrt(2) / 2) = 135.00000000000000000000000000000000000000000000005500 |
acos(-sqrt(2) / 2) = 135.00000000000000000000000000000000000000000000005500 |
||
atan(sqrt(3)) = 60.00000000000000000000000000000000000000000000002463</pre> |
atan(sqrt(3)) = 60.00000000000000000000000000000000000000000000002463</pre> |
||
=={{header|BQN}}== |
|||
BQN has a system value <code>•math</code> which contains trigonometry functions. Inputs are given in radians. These functions can also be used with BQN's Inverse modifier (<code>⁼</code>) to get their respective defined inverses. |
|||
Some results may be inaccurate due to floating point issues. |
|||
The following is done in the BQN REPL: |
|||
<syntaxhighlight lang="bqn"> ⟨sin, cos, tan⟩ ← •math |
|||
Sin 0 |
|||
0 |
|||
Sin π÷2 |
|||
1 |
|||
Cos 0 |
|||
1 |
|||
Cos π÷2 |
|||
6.123233995736766e¯17 |
|||
Tan 0 |
|||
0 |
|||
Tan π÷2 |
|||
16331239353195370 |
|||
Sin⁼ 0 |
|||
0 |
|||
Sin⁼ 1 |
|||
1.5707963267948966 |
|||
Cos⁼ 1 |
|||
0 |
|||
Cos⁼ 0 |
|||
1.5707963267948966 |
|||
Tan⁼ 0 |
|||
0 |
|||
Tan⁼ ∞ |
|||
1.5707963267948966</syntaxhighlight> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <math.h> |
||
#include <stdio.h> |
#include <stdio.h> |
||
Line 440: | Line 894: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
0.707107 0.707107 |
0.707107 0.707107 |
||
Line 451: | Line 905: | ||
0.785398 45.000000 |
0.785398 45.000000 |
||
</pre> |
</pre> |
||
=={{header|C sharp|C#}}== |
|||
<syntaxhighlight 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(); |
|||
} |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <cmath> |
#include <cmath> |
||
Line 483: | Line 964: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|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> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
{{trans|fortran}} |
{{trans|fortran}} |
||
< |
<syntaxhighlight lang="lisp">(ns user |
||
(:require [clojure.contrib.generic.math-functions :as generic])) |
(:require [clojure.contrib.generic.math-functions :as generic])) |
||
Line 530: | Line 985: | ||
(println (str (asin (sin radians) ) " " (* (asin (sin (* degrees dtor))) rtod))) |
(println (str (asin (sin radians) ) " " (* (asin (sin (* degrees dtor))) rtod))) |
||
(println (str (acos (cos radians) ) " " (* (acos (cos (* degrees dtor))) rtod))) |
(println (str (acos (cos radians) ) " " (* (acos (cos (* degrees dtor))) rtod))) |
||
(println (str (atan (tan radians) ) " " (* (atan (tan (* degrees dtor))) rtod)))</ |
(println (str (atan (tan radians) ) " " (* (atan (tan (* degrees dtor))) rtod)))</syntaxhighlight> |
||
{{out}} (matches that of Java) |
|||
0.7071067811865475 0.7071067811865475 |
0.7071067811865475 0.7071067811865475 |
||
0.7071067811865476 0.7071067811865476 |
0.7071067811865476 0.7071067811865476 |
||
Line 542: | Line 997: | ||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. Trig. |
PROGRAM-ID. Trig. |
||
Line 580: | Line 1,035: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
Radians: |
Radians: |
||
Line 601: | Line 1,056: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun deg->rad (x) (* x (/ pi 180))) |
||
(defun rad->deg (x) (* x (/ 180 pi))) |
(defun rad->deg (x) (* x (/ 180 pi))) |
||
Line 616: | Line 1,071: | ||
(rad->deg (acos 1/2)) |
(rad->deg (acos 1/2)) |
||
(atan 15) |
(atan 15) |
||
(rad->deg (atan 15))))</ |
(rad->deg (atan 15))))</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
{{trans|C}} |
{{trans|C}} |
||
<syntaxhighlight lang="d">void main() { |
|||
<lang d>import std.stdio, std.math; |
|||
import std.stdio, std.math; |
|||
enum degrees = 45.0L; |
|||
void main() { |
|||
enum |
enum t0 = degrees * PI / 180.0L; |
||
enum real t0 = degrees * PI / 180.0; |
|||
writeln("Reference: 0.7071067811865475244008"); |
writeln("Reference: 0.7071067811865475244008"); |
||
writefln("Sine: %.20f %.20f", |
writefln("Sine: %.20f %.20f", PI_4.sin, t0.sin); |
||
writefln("Cosine: %.20f %.20f", |
writefln("Cosine: %.20f %.20f", PI_4.cos, t0.cos); |
||
writefln("Tangent: %.20f %.20f", |
writefln("Tangent: %.20f %.20f", PI_4.tan, t0.tan); |
||
writeln |
writeln; |
||
writeln("Reference: 0.7853981633974483096156"); |
writeln("Reference: 0.7853981633974483096156"); |
||
immutable real t1 = |
immutable real t1 = PI_4.sin.asin; |
||
writefln("Arcsine: %.20f %.20f", t1, t1 * 180. |
writefln("Arcsine: %.20f %.20f", t1, t1 * 180.0L / PI); |
||
immutable real t2 = |
immutable real t2 = PI_4.cos.acos; |
||
writefln("Arccosine: %.20f %.20f", t2, t2 * 180. |
writefln("Arccosine: %.20f %.20f", t2, t2 * 180.0L / PI); |
||
immutable real t3 = |
immutable real t3 = PI_4.tan.atan; |
||
writefln("Arctangent: %.20f %.20f", t3, t3 * 180. |
writefln("Arctangent: %.20f %.20f", t3, t3 * 180.0L / PI); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>Reference: 0.7071067811865475244008 |
<pre>Reference: 0.7071067811865475244008 |
||
Sine: 0.70710678118654752442 0.70710678118654752442 |
Sine: 0.70710678118654752442 0.70710678118654752442 |
||
Line 651: | Line 1,106: | ||
Arccosine: 0.78539816339744830961 45.00000000000000000000 |
Arccosine: 0.78539816339744830961 45.00000000000000000000 |
||
Arctangent: 0.78539816339744830961 45.00000000000000000000</pre> |
Arctangent: 0.78539816339744830961 45.00000000000000000000</pre> |
||
=={{header|Delphi}}== |
|||
{{works with|Delphi|6.0}} |
|||
{{libheader|SysUtils,StdCtrls}} |
|||
<syntaxhighlight lang="Delphi"> |
|||
procedure ShowTrigFunctions(Memo: TMemo); |
|||
const AngleDeg = 45.0; |
|||
var AngleRad,ArcSine,ArcCosine,ArcTangent: double; |
|||
begin |
|||
AngleRad:=DegToRad(AngleDeg); |
|||
Memo.Lines.Add(Format('Angle: Degrees: %3.5f Radians: %3.6f',[AngleDeg,AngleRad])); |
|||
Memo.Lines.Add('-------------------------------------------------'); |
|||
Memo.Lines.Add(Format('Sine: Degrees: %3.6f Radians: %3.6f',[sin(DegToRad(AngleDeg)),sin(AngleRad)])); |
|||
Memo.Lines.Add(Format('Cosine: Degrees: %3.6f Radians: %3.6f',[cos(DegToRad(AngleDeg)),cos(AngleRad)])); |
|||
Memo.Lines.Add(Format('Tangent: Degrees: %3.6f Radians: %3.6f',[tan(DegToRad(AngleDeg)),tan(AngleRad)])); |
|||
ArcSine:=ArcSin(Sin(AngleRad)); |
|||
Memo.Lines.Add(Format('Arcsine: Degrees: %3.6f Radians: %3.6f',[DegToRad(ArcSine),ArcSine])); |
|||
ArcCosine:=ArcCos(cos(AngleRad)); |
|||
Memo.Lines.Add(Format('Arccosine: Degrees: %3.6f Radians: %3.6f',[DegToRad(ArcCosine),ArcCosine])); |
|||
ArcTangent:=ArcTan(tan(AngleRad)); |
|||
Memo.Lines.Add(Format('Arctangent: Degrees: %3.6f Radians: %3.6f',[DegToRad(ArcTangent),ArcTangent])); |
|||
end; |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Angle: Degrees: 45.00000 Radians: 0.785398 |
|||
------------------------------------------------- |
|||
Sine: Degrees: 0.707107 Radians: 0.707107 |
|||
Cosine: Degrees: 0.707107 Radians: 0.707107 |
|||
Tangent: Degrees: 1.000000 Radians: 1.000000 |
|||
Arcsine: Degrees: 0.013708 Radians: 0.785398 |
|||
Arccosine: Degrees: 0.013708 Radians: 0.785398 |
|||
Arctangent: Degrees: 0.013708 Radians: 0.785398 |
|||
Elapsed Time: 9.118 ms. |
|||
</pre> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
{{trans|ALGOL 68}} |
{{trans|ALGOL 68}} |
||
< |
<syntaxhighlight lang="e">def pi := (-1.0).acos() |
||
def radians := pi / 4.0 |
def radians := pi / 4.0 |
||
Line 670: | Line 1,170: | ||
${def acos := radians.cos().acos()} ${r2d(acos)} |
${def acos := radians.cos().acos()} ${r2d(acos)} |
||
${def atan := radians.tan().atan()} ${r2d(atan)} |
${def atan := radians.tan().atan()} ${r2d(atan)} |
||
`)</ |
`)</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
0.7071067811865475 0.7071067811865475 |
0.7071067811865475 0.7071067811865475 |
||
0.7071067811865476 0.7071067811865476 |
0.7071067811865476 0.7071067811865476 |
||
Line 679: | Line 1,179: | ||
0.7853981633974483 45.0 |
0.7853981633974483 45.0 |
||
0.7853981633974483 45.0 |
0.7853981633974483 45.0 |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight> |
|||
r = pi / 4 |
|||
d = 45 |
|||
# |
|||
func r2d r . |
|||
return r / pi * 180 |
|||
. |
|||
func d2r d . |
|||
return d * pi / 180 |
|||
. |
|||
# |
|||
numfmt 4 0 |
|||
print sin d & " " & sin r2d r |
|||
print cos d & " " & cos r2d r |
|||
print tan d & " " & tan r2d r |
|||
print "" |
|||
h = asin sin d |
|||
print h & " " & d2r h |
|||
h = acos cos d |
|||
print h & " " & d2r h |
|||
h = atan tan d |
|||
print h & " " & d2r h |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0.7071 0.7071 |
|||
0.7071 0.7071 |
|||
1.0000 1.0000 |
|||
45.0000 0.7854 |
|||
45 0.7854 |
|||
45 0.7854 |
|||
</pre> |
|||
=={{header|Elena}}== |
|||
{{trans|C++}} |
|||
ELENA 4.x: |
|||
<syntaxhighlight lang="elena">import system'math; |
|||
import extensions; |
|||
public program() |
|||
{ |
|||
console.printLine("Radians:"); |
|||
console.printLine("sin(π/3) = ",(Pi_value/3).sin()); |
|||
console.printLine("cos(π/3) = ",(Pi_value/3).cos()); |
|||
console.printLine("tan(π/3) = ",(Pi_value/3).tan()); |
|||
console.printLine("arcsin(1/2) = ",0.5r.arcsin()); |
|||
console.printLine("arccos(1/2) = ",0.5r.arccos()); |
|||
console.printLine("arctan(1/2) = ",0.5r.arctan()); |
|||
console.printLine(); |
|||
console.printLine("Degrees:"); |
|||
console.printLine("sin(60º) = ",60.0r.Radian.sin()); |
|||
console.printLine("cos(60º) = ",60.0r.Radian.cos()); |
|||
console.printLine("tan(60º) = ",60.0r.Radian.tan()); |
|||
console.printLine("arcsin(1/2) = ",0.5r.arcsin().Degree,"º"); |
|||
console.printLine("arccos(1/2) = ",0.5r.arccos().Degree,"º"); |
|||
console.printLine("arctan(1/2) = ",0.5r.arctan().Degree,"º"); |
|||
console.readChar() |
|||
}</syntaxhighlight> |
|||
=={{header|Elixir}}== |
|||
{{trans|Erlang}} |
|||
<syntaxhighlight lang="elixir">iex(61)> deg = 45 |
|||
45 |
|||
iex(62)> rad = :math.pi / 4 |
|||
0.7853981633974483 |
|||
iex(63)> :math.sin(deg * :math.pi / 180) == :math.sin(rad) |
|||
true |
|||
iex(64)> :math.cos(deg * :math.pi / 180) == :math.cos(rad) |
|||
true |
|||
iex(65)> :math.tan(deg * :math.pi / 180) == :math.tan(rad) |
|||
true |
|||
iex(66)> temp = :math.acos(:math.cos(rad)) |
|||
0.7853981633974483 |
|||
iex(67)> temp * 180 / :math.pi == deg |
|||
true |
|||
iex(68)> temp = :math.atan(:math.tan(rad)) |
|||
0.7853981633974483 |
|||
iex(69)> temp * 180 / :math.pi == deg |
|||
true</syntaxhighlight> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="erlang"> |
||
Deg=45. |
Deg=45. |
||
Rad=math:pi()/4. |
Rad=math:pi()/4. |
||
math:sin(Deg * math:pi() / 180)==math:sin(Rad). |
math:sin(Deg * math:pi() / 180)==math:sin(Rad). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
|||
Output: |
|||
true |
true |
||
< |
<syntaxhighlight lang="erlang"> |
||
math:cos(Deg * math:pi() / 180)==math:cos(Rad). |
math:cos(Deg * math:pi() / 180)==math:cos(Rad). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
|||
Output: |
|||
true |
true |
||
< |
<syntaxhighlight lang="erlang"> |
||
math:tan(Deg * math:pi() / 180)==math:tan(Rad). |
math:tan(Deg * math:pi() / 180)==math:tan(Rad). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
|||
Output: |
|||
true |
true |
||
< |
<syntaxhighlight lang="erlang"> |
||
Temp = math:acos(math:cos(Rad)). |
Temp = math:acos(math:cos(Rad)). |
||
Temp * 180 / math:pi()==Deg. |
Temp * 180 / math:pi()==Deg. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
|||
Output: |
|||
true |
true |
||
< |
<syntaxhighlight lang="erlang"> |
||
Temp = math:atan(math:tan(Rad)). |
Temp = math:atan(math:tan(Rad)). |
||
Temp * 180 / math:pi()==Deg. |
Temp * 180 / math:pi()==Deg. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
|||
Output: |
|||
true |
true |
||
=={{header| |
=={{header|F_Sharp|F#}}== |
||
<syntaxhighlight lang="fsharp">open NUnit.Framework |
|||
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> |
|||
=={{header|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> |
|||
=={{header|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> |
|||
=={{header|F sharp|F#}}== |
|||
<lang fsharp>open NUnit.Framework |
|||
open FsUnit |
open FsUnit |
||
Line 914: | Line 1,429: | ||
let c = System.Math.Cos (toRadians 45.0) |
let c = System.Math.Cos (toRadians 45.0) |
||
let s = System.Math.Sin (toRadians 45.0) |
let s = System.Math.Sin (toRadians 45.0) |
||
System.Math.Round(c,5) = System.Math.Round(s,5) |> should be True</ |
System.Math.Round(c,5) = System.Math.Round(s,5) |> should be True</syntaxhighlight> |
||
=={{header|Factor}}== |
|||
<syntaxhighlight lang="factor">USING: kernel math math.constants math.functions math.trig |
|||
prettyprint ; |
|||
pi 4 / 45 deg>rad [ sin ] [ cos ] [ tan ] |
|||
[ [ . ] compose dup compose ] tri@ 2tri |
|||
.5 [ asin ] [ acos ] [ atan ] tri [ dup rad>deg [ . ] bi@ ] tri@</syntaxhighlight> |
|||
=={{header|Fantom}}== |
|||
Fantom's Float library includes all six trigonometric functions, |
|||
which assume the number is in radians. <br> |
|||
Methods are provided to convert: toDegrees and toRadians. |
|||
<syntaxhighlight 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) |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Forth}}== |
|||
<syntaxhighlight 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] )</syntaxhighlight> |
|||
=={{header|Fortran}}== |
|||
Trigonometic functions expect arguments in radians so degrees require conversion |
|||
<syntaxhighlight 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</syntaxhighlight> |
|||
{{out}} |
|||
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 |
|||
<syntaxhighlight lang="fortran"> ATAN2(y,x) ! Arctangent(y/x), ''-pi < result <= +pi'' |
|||
SINH(x) ! Hyperbolic sine |
|||
COSH(x) ! Hyperbolic cosine |
|||
TANH(x) ! Hyperbolic tangent</syntaxhighlight> |
|||
But, for those with access to fatter Fortran function libraries, trigonometrical functions working in degrees are also available. |
|||
<syntaxhighlight lang="fortran"> |
|||
Calculate various trigonometric functions from the Fortran library. |
|||
INTEGER BIT(32),B,IP !Stuff for bit fiddling. |
|||
INTEGER ENUFF,I !Step through the test angles. |
|||
PARAMETER (ENUFF = 17) !A selection of special values. |
|||
INTEGER ANGLE(ENUFF) !All in whole degrees. |
|||
DATA ANGLE/0,30,45,60,90,120,135,150,180, !Here they are. |
|||
1 210,225,240,270,300,315,330,360/ !Thus check angle folding. |
|||
REAL PI,DEG2RAD !Special numbers. |
|||
REAL D,R,FD,FR,AD,AR !Degree, Radian, F(D), F(R), inverses. |
|||
PI = 4*ATAN(1.0) !SINGLE PRECISION 1·0. |
|||
DEG2RAD = PI/180 !Limited precision here too for a transcendental number. |
|||
Case the first: sines. |
|||
WRITE (6,10) ("Sin", I = 1,4) !Supply some names. |
|||
10 FORMAT (" Deg.",A7,"(Deg)",A7,"(Rad) Rad - Deg", !Ah, layout. |
|||
1 6X,"Arc",A3,"D",6X,"Arc",A3,"R",9X,"Diff") |
|||
DO I = 1,ENUFF !Step through the test values. |
|||
D = ANGLE(I) !The angle in degrees, in floating point. |
|||
R = D*DEG2RAD !Approximation, in radians. |
|||
FD = SIND(D); AD = ASIND(FD) !Functions working in degrees. |
|||
FR = SIN(R); AR = ASIN(FR)/DEG2RAD !Functions working in radians. |
|||
WRITE (6,11) INT(D),FD,FR,FR - FD,AD,AR,AR - AD !Results. |
|||
11 FORMAT (I4,":",3F12.8,3F13.7) !Ah, alignment with FORMAT 10... |
|||
END DO !On to the next test value. |
|||
Case the second: cosines. |
|||
WRITE (6,10) ("Cos", I = 1,4) |
|||
DO I = 1,ENUFF |
|||
D = ANGLE(I) |
|||
R = D*DEG2RAD |
|||
FD = COSD(D); AD = ACOSD(FD) |
|||
FR = COS(R); AR = ACOS(FR)/DEG2RAD |
|||
WRITE (6,11) INT(D),FD,FR,FR - FD,AD,AR,AR - AD |
|||
END DO |
|||
Case the third: tangents. |
|||
WRITE (6,10) ("Tan", I = 1,4) |
|||
DO I = 1,ENUFF |
|||
D = ANGLE(I) |
|||
R = D*DEG2RAD |
|||
FD = TAND(D); AD = ATAND(FD) |
|||
FR = TAN(R); AR = ATAN(FR)/DEG2RAD |
|||
WRITE (6,11) INT(D),FD,FR,FR - FD,AD,AR,AR - AD |
|||
END DO |
|||
WRITE (6,*) "...Special deal for 90 degrees..." |
|||
D = 90 |
|||
R = D*DEG2RAD |
|||
FD = TAND(D); AD = ATAND(FD) |
|||
FR = TAN(R); AR = ATAN(FR)/DEG2RAD |
|||
WRITE (6,*) "TanD =",FD,"Atan =",AD |
|||
WRITE (6,*) "TanR =",FR,"Atan =",AR |
|||
Convert PI to binary... |
|||
PI = PI - 3 !I know it starts with three, and I need the fractional part. |
|||
BIT(1:2) = 1 !So, the binary is 11. something. |
|||
B = 2 !Two bits known. |
|||
DO I = 1,26 !For single precision, more than enough additional bits. |
|||
PI = PI*2 !Hoist a bit to the hot spot. |
|||
IP = PI !The integral part. |
|||
PI = PI - IP !Remove it from the work in progress. |
|||
B = B + 1 !Another bit bitten. |
|||
BIT(B) = IP !Place it. |
|||
END DO !On to the next. |
|||
WRITE (6,20) BIT(1:B) !Reveal the bits. |
|||
20 FORMAT (" Pi ~ ",2I1,".",66I1) !A known format. |
|||
WRITE (6,*) " = 11.00100100001111110110101010001000100001..." !But actually... |
|||
END !So much for that. |
|||
</syntaxhighlight> |
|||
Output: |
|||
Deg. Sin(Deg) Sin(Rad) Rad - Deg ArcSinD ArcSinR Diff |
|||
0: 0.00000000 0.00000000 0.00000000 0.0000000 0.0000000 0.0000000 |
|||
30: 0.50000000 0.50000000 0.00000000 30.0000000 30.0000000 0.0000000 |
|||
45: 0.70710677 0.70710677 0.00000000 45.0000000 45.0000000 0.0000000 |
|||
60: 0.86602539 0.86602545 0.00000006 60.0000000 60.0000038 0.0000038 |
|||
90: 1.00000000 1.00000000 0.00000000 90.0000000 90.0000000 0.0000000 |
|||
120: 0.86602539 0.86602539 0.00000000 60.0000000 60.0000000 0.0000000 |
|||
135: 0.70710677 0.70710677 0.00000000 45.0000000 45.0000000 0.0000000 |
|||
150: 0.50000000 0.50000006 0.00000006 30.0000000 30.0000038 0.0000038 |
|||
180: 0.00000000 -0.00000009 -0.00000009 0.0000000 -0.0000050 -0.0000050 |
|||
210: -0.50000000 -0.49999997 0.00000003 -30.0000000 -29.9999981 0.0000019 |
|||
225: -0.70710677 -0.70710671 0.00000006 -45.0000000 -44.9999962 0.0000038 |
|||
240: -0.86602539 -0.86602545 -0.00000006 -60.0000000 -60.0000038 -0.0000038 |
|||
270: -1.00000000 -1.00000000 0.00000000 -90.0000000 -90.0000000 0.0000000 |
|||
300: -0.86602539 -0.86602545 -0.00000006 -60.0000000 -60.0000038 -0.0000038 |
|||
315: -0.70710677 -0.70710689 -0.00000012 -45.0000000 -45.0000076 -0.0000076 |
|||
330: -0.50000000 -0.50000018 -0.00000018 -30.0000000 -30.0000114 -0.0000114 |
|||
360: 0.00000000 0.00000017 0.00000017 0.0000000 0.0000100 0.0000100 |
|||
Deg. Cos(Deg) Cos(Rad) Rad - Deg ArcCosD ArcCosR Diff |
|||
0: 1.00000000 1.00000000 0.00000000 0.0000000 0.0000000 0.0000000 |
|||
30: 0.86602539 0.86602539 0.00000000 30.0000019 30.0000019 0.0000000 |
|||
45: 0.70710677 0.70710677 0.00000000 45.0000000 45.0000000 0.0000000 |
|||
60: 0.50000000 0.49999997 -0.00000003 60.0000000 60.0000038 0.0000038 |
|||
90: 0.00000000 -0.00000004 -0.00000004 90.0000000 90.0000000 0.0000000 |
|||
120: -0.50000000 -0.50000006 -0.00000006 120.0000000 120.0000076 0.0000076 |
|||
135: -0.70710677 -0.70710677 0.00000000 135.0000000 135.0000000 0.0000000 |
|||
150: -0.86602539 -0.86602539 0.00000000 150.0000000 150.0000000 0.0000000 |
|||
180: -1.00000000 -1.00000000 0.00000000 180.0000000 180.0000000 0.0000000 |
|||
210: -0.86602539 -0.86602539 0.00000000 150.0000000 150.0000000 0.0000000 |
|||
225: -0.70710677 -0.70710683 -0.00000006 135.0000000 135.0000000 0.0000000 |
|||
240: -0.50000000 -0.49999991 0.00000009 120.0000000 119.9999924 -0.0000076 |
|||
270: 0.00000000 0.00000001 0.00000001 90.0000000 90.0000000 0.0000000 |
|||
300: 0.50000000 0.49999991 -0.00000009 60.0000000 60.0000076 0.0000076 |
|||
315: 0.70710677 0.70710665 -0.00000012 45.0000000 45.0000114 0.0000114 |
|||
330: 0.86602539 0.86602533 -0.00000006 30.0000019 30.0000095 0.0000076 |
|||
360: 1.00000000 1.00000000 0.00000000 0.0000000 0.0000000 0.0000000 |
|||
Deg. Tan(Deg) Tan(Rad) Rad - Deg ArcTanD ArcTanR Diff |
|||
0: 0.00000000 0.00000000 0.00000000 0.0000000 0.0000000 0.0000000 |
|||
30: 0.57735026 0.57735026 0.00000000 30.0000000 30.0000000 0.0000000 |
|||
45: 1.00000000 1.00000000 0.00000000 45.0000000 45.0000000 0.0000000 |
|||
60: 1.73205078 1.73205090 0.00000012 60.0000000 60.0000000 0.0000000 |
|||
90:************************************ 90.0000000 -90.0000000 -180.0000000 |
|||
120: -1.73205078 -1.73205054 0.00000024 -60.0000000 -59.9999962 0.0000038 |
|||
135: -1.00000000 -1.00000000 0.00000000 -45.0000000 -45.0000000 0.0000000 |
|||
150: -0.57735026 -0.57735032 -0.00000006 -30.0000000 -30.0000019 -0.0000019 |
|||
180: 0.00000000 0.00000009 0.00000009 0.0000000 0.0000050 0.0000050 |
|||
210: 0.57735026 0.57735026 0.00000000 30.0000000 30.0000000 0.0000000 |
|||
225: 1.00000000 0.99999988 -0.00000012 45.0000000 44.9999962 -0.0000038 |
|||
240: 1.73205078 1.73205125 0.00000048 60.0000000 60.0000076 0.0000076 |
|||
270:************************************ 90.0000000 -90.0000000 -180.0000000 |
|||
300: -1.73205078 -1.73205113 -0.00000036 -60.0000000 -60.0000038 -0.0000038 |
|||
315: -1.00000000 -1.00000024 -0.00000024 -45.0000000 -45.0000076 -0.0000076 |
|||
330: -0.57735026 -0.57735056 -0.00000030 -30.0000000 -30.0000134 -0.0000134 |
|||
360: 0.00000000 0.00000017 0.00000017 0.0000000 0.0000100 0.0000100 |
|||
...Special deal for 90 degrees... |
|||
TanD = 1.6331778E+16 Atan = 90.00000 |
|||
TanR = -2.2877332E+07 Atan = -90.00000 |
|||
Pi ~ 11.00100100001111110110110000 |
|||
= 11.00100100001111110110101010001000100001... |
|||
Notice that the calculations in radians are less accurate. Firstly, pi cannot be represented exactly and secondly, the conversion factor of pi/180 or 180/pi adds further to the error. The degree-based functions obviously can fold their angles using exact arithmetic (though ACosD has surprising trouble with 30°) and so 360° is the same as 0°, unlike the case with radians. TanD(90°) should yield Infinity (but, which sign?) but perhaps this latter-day feature of computer floating-point was not included. In any case, Tan(90° in radians) faces the problem that its parameter will not in fact be pi/2 but some value just over (or under), and likewise with double precision and quadruple precision and any other finite precision. |
|||
=={{header|FreeBASIC}}== |
|||
{{trans|C}} |
|||
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
|||
Const pi As Double = 4 * Atn(1) |
|||
Dim As Double radians = pi / 4 |
|||
Dim As Double degrees = 45.0 '' equivalent in degrees |
|||
Dim As Double temp |
|||
Print "Radians : "; radians, " "; |
|||
Print "Degrees : "; degrees |
|||
Print |
|||
Print "Sine : "; Sin(radians), Sin(degrees * pi / 180) |
|||
Print "Cosine : "; Cos(radians), Cos(degrees * pi / 180) |
|||
Print "Tangent : "; Tan(radians), Tan(degrees * pi / 180) |
|||
Print |
|||
temp = ASin(Sin(radians)) |
|||
Print "Arc Sine : "; temp, temp * 180 / pi |
|||
temp = ACos(Cos(radians)) |
|||
Print "Arc Cosine : "; temp, temp * 180 / pi |
|||
temp = Atn(Tan(radians)) |
|||
Print "Arc Tangent : "; temp, temp * 180 / pi |
|||
Sleep</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Radians : 0.7853981633974483 Degrees : 45 |
|||
Sine : 0.7071067811865475 0.7071067811865475 |
|||
Cosine : 0.7071067811865476 0.7071067811865476 |
|||
Tangent : 0.9999999999999999 0.9999999999999999 |
|||
Arc Sine : 0.7853981633974482 44.99999999999999 |
|||
Arc Cosine : 0.7853981633974483 45 |
|||
Arc Tangent : 0.7853981633974483 45 |
|||
</pre> |
|||
=={{header|FutureBasic}}== |
|||
<syntaxhighlight lang="futurebasic"> |
|||
include "NSLog.incl" |
|||
void local fn DoIt |
|||
double degrees = 45.0 |
|||
double radians = degrees * M_PI / 180 |
|||
NSLog(@"%f, %f",sin(radians),sin(degrees * M_PI / 180)) |
|||
NSLog(@"%f, %f",cos(radians),cos(degrees * M_PI / 180)) |
|||
NSLog(@"%f, %f",tan(radians),tan(degrees * M_PI / 180)) |
|||
NSLog(@"%f, %f",asin(sin(radians)),asin(sin(radians)) * 180 / M_PI) |
|||
NSLog(@"%f, %f",acos(cos(radians)),acos(cos(radians)) * 180 / M_PI) |
|||
NSLog(@"%f, %f",atan(tan(radians)),atan(tan(radians)) * 180 / M_PI) |
|||
end fn |
|||
fn DoIt |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0.707107, 0.707107 |
|||
0.707107, 0.707107 |
|||
1.000000, 1.000000 |
|||
0.785398, 45.000000 |
|||
0.785398, 45.000000 |
|||
0.785398, 45.000000 |
|||
</pre> |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap"># GAP has an improved floating-point support since version 4.5 |
||
Pi := Acos(-1.0); |
Pi := Acos(-1.0); |
||
# Or use the built-in constant: |
|||
Pi := FLOAT.PI; |
|||
r := Pi / 5.0; |
r := Pi / 5.0; |
||
Line 931: | Line 1,727: | ||
Cos(Deg(d)); Acos(last); |
Cos(Deg(d)); Acos(last); |
||
Tan(r); Atan(last); |
Tan(r); Atan(last); |
||
Tan(Deg(d)); Atan(last);</ |
Tan(Deg(d)); Atan(last);</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|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 [http://golang.org/pkg/math/#Sincos Sincos] function. |
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 [http://golang.org/pkg/math/#Sincos Sincos] function. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 962: | Line 1,758: | ||
fmt.Printf("atan(%f) = %9.6f deg\n", t, math.Atan(t)*180/math.Pi) |
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)) |
fmt.Printf("atan(%f) = %9.6f rad\n", t, math.Atan(t)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
sin(30.000000 deg) = 0.500000 |
sin(30.000000 deg) = 0.500000 |
||
Line 981: | Line 1,777: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Trig functions use radians, degrees must be converted to/from radians |
Trig functions use radians, degrees must be converted to/from radians |
||
< |
<syntaxhighlight lang="groovy">def radians = Math.PI/4 |
||
def degrees = 45 |
def degrees = 45 |
||
Line 992: | Line 1,788: | ||
println "asin(\u221A2/2) = ${Math.asin(2**(-0.5))} == asin(\u221A2/2)\u00B0 = ${r2d(Math.asin(2**(-0.5)))}\u00B0" |
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 "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"</ |
println "atan(1) = ${Math.atan(1)} == atan(1)\u00B0 = ${r2d(Math.atan(1))}\u00B0"</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>sin(π/4) = 0.7071067811865475 == sin(45°) = 0.7071067811865475 |
<pre>sin(π/4) = 0.7071067811865475 == sin(45°) = 0.7071067811865475 |
||
cos(π/4) = 0.7071067811865476 == cos(45°) = 0.7071067811865476 |
cos(π/4) = 0.7071067811865476 == cos(45°) = 0.7071067811865476 |
||
Line 1,006: | Line 1,802: | ||
Trigonometric functions use radians; degrees require conversion. |
Trigonometric functions use radians; degrees require conversion. |
||
< |
<syntaxhighlight lang="haskell">fromDegrees :: Floating a => a -> a |
||
fromDegrees deg = deg * pi / 180 |
|||
toDegrees :: Floating a => a -> a |
|||
toDegrees rad = rad * 180 / pi |
|||
main :: IO () |
|||
example = [ |
|||
main = |
|||
sin (pi / 6), sin (fromDegrees 30), |
|||
mapM_ |
|||
cos (pi / 6), cos (fromDegrees 30), |
|||
print |
|||
tan (pi / 6), tan (fromDegrees 30), |
|||
[ 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) |
|||
]</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>0.49999999999999994 |
|||
0.49999999999999994 |
|||
0.8660254037844387 |
|||
0.8660254037844387 |
|||
0.5773502691896256 |
|||
0.5773502691896256 |
|||
0.5235987755982988 |
|||
29.999999999999996 |
|||
1.0471975511965976 |
|||
59.99999999999999 |
|||
0.46364760900080615 |
|||
26.56505117707799</pre> |
|||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
Translated from Fortran: |
Translated from Fortran: |
||
< |
<syntaxhighlight lang="hicest">pi = 4.0 * ATAN(1.0) |
||
dtor = pi / 180.0 |
dtor = pi / 180.0 |
||
rtod = 180.0 / pi |
rtod = 180.0 / pi |
||
Line 1,030: | Line 1,852: | ||
WRITE(ClipBoard) ASIN(SIN(radians)), ASIN(SIN(degrees*dtor))*rtod |
WRITE(ClipBoard) ASIN(SIN(radians)), ASIN(SIN(degrees*dtor))*rtod |
||
WRITE(ClipBoard) ACOS(COS(radians)), ACOS(COS(degrees*dtor))*rtod |
WRITE(ClipBoard) ACOS(COS(radians)), ACOS(COS(degrees*dtor))*rtod |
||
WRITE(ClipBoard) ATAN(TAN(radians)), ATAN(TAN(degrees*dtor))*rtod</ |
WRITE(ClipBoard) ATAN(TAN(radians)), ATAN(TAN(degrees*dtor))*rtod</syntaxhighlight> |
||
< |
<syntaxhighlight lang="hicest">0.7071067812 0.7071067812 |
||
0.7071067812 0.7071067812 |
0.7071067812 0.7071067812 |
||
1 1 |
1 1 |
||
0.7853981634 45 |
0.7853981634 45 |
||
0.7853981634 45 |
0.7853981634 45 |
||
0.7853981634 45</ |
0.7853981634 45</syntaxhighlight> |
||
SINH, COSH, TANH, and inverses are available as well. |
SINH, COSH, TANH, and inverses are available as well. |
||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
< |
<syntaxhighlight lang="idl">deg = 35 ; arbitrary number of degrees |
||
rad = !dtor*deg ; system variables !dtor and !radeg convert between rad and deg</ |
rad = !dtor*deg ; system variables !dtor and !radeg convert between rad and deg</syntaxhighlight> |
||
< |
<syntaxhighlight lang="idl">; the trig functions receive and emit radians: |
||
print, rad, sin(rad), asin(sin(rad)) |
print, rad, sin(rad), asin(sin(rad)) |
||
print, cos(rad), acos(cos(rad)) |
print, cos(rad), acos(cos(rad)) |
||
Line 1,051: | Line 1,873: | ||
; 0.610865 0.573576 0.610865 |
; 0.610865 0.573576 0.610865 |
||
; 0.819152 0.610865 |
; 0.819152 0.610865 |
||
; 0.700208 0.610865</ |
; 0.700208 0.610865</syntaxhighlight> |
||
< |
<syntaxhighlight lang="idl">; the hyperbolic versions exist and behave as expected: |
||
print, sinh(rad) ; etc |
print, sinh(rad) ; etc |
||
; outputs |
; outputs |
||
; 0.649572</ |
; 0.649572</syntaxhighlight> |
||
< |
<syntaxhighlight 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... |
x = !dpi/[[2,3],[4,5],[6,7]] ; !dpi is a read-only sysvar = 3.1415... |
||
print,sin(x) |
print,sin(x) |
||
Line 1,064: | Line 1,886: | ||
; 1.0000000 0.86602540 |
; 1.0000000 0.86602540 |
||
; 0.70710678 0.58778525 |
; 0.70710678 0.58778525 |
||
; 0.50000000 0.43388374</ |
; 0.50000000 0.43388374</syntaxhighlight> |
||
< |
<syntaxhighlight lang="idl">; the trig functions behave as expected for complex arguments: |
||
x = complex(1,2) |
x = complex(1,2) |
||
print,sin(x) |
print,sin(x) |
||
; outputs |
; outputs |
||
; ( 3.16578, 1.95960)</ |
; ( 3.16578, 1.95960)</syntaxhighlight> |
||
== Icon and Unicon == |
== 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 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: |
||
==={{header|Icon}}=== |
==={{header|Icon}}=== |
||
< |
<syntaxhighlight lang="icon">invocable all |
||
procedure main() |
procedure main() |
||
Line 1,082: | Line 1,904: | ||
every write(f := !["sin","cos","tan"],"(",r,")=",y := f(r)," ",fi := "a" || f,"(",y,")=",x := fi(y)," rad = ",rtod(x)," deg") |
every write(f := !["sin","cos","tan"],"(",r,")=",y := f(r)," ",fi := "a" || f,"(",y,")=",x := fi(y)," rad = ",rtod(x)," deg") |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
|||
Sample Output:<pre>sin(0.5235987755982988)=0.4999999999999999 asin(0.4999999999999999)=0.5235987755982988 rad = 30.0 deg |
|||
<pre>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 |
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</pre> |
tan(0.5235987755982988)=0.5773502691896257 atan(0.5773502691896257)=0.5235987755982988 rad = 30.0 deg</pre> |
||
==={{header|Unicon}}=== |
==={{header|Unicon}}=== |
||
The Icon solution works in Unicon. |
The Icon solution works in Unicon. |
||
Line 1,093: | Line 1,917: | ||
Sine, cosine, and tangent of a single angle, indicated as pi-over-four radians and as 45 degrees: |
Sine, cosine, and tangent of a single angle, indicated as pi-over-four radians and as 45 degrees: |
||
< |
<syntaxhighlight lang="j"> (1&o. , 2&o. ,: 3&o.) (4 %~ o. 1) , 180 %~ o. 45 |
||
0.707107 0.707107 |
|||
0.707107 0.707107 |
|||
1 1</syntaxhighlight> |
|||
Arcsine, arccosine, and arctangent of one-half, in radians and degrees: |
Arcsine, arccosine, and arctangent of one-half, in radians and degrees: |
||
< |
<syntaxhighlight lang="j"> ([ ,. 180p_1&*) (_1&o. , _2&o. ,: _3&o.) 0.5 |
||
0.523599 30 |
|||
1.0472 60 |
|||
0.463648 26.5651</syntaxhighlight> |
|||
The <code>trig</code> script adds cover functions for the trigonometric operations as well as verbs for converting degrees from radians (<code>dfr</code>) and radians from degrees (<code>rfd</code>) |
|||
<syntaxhighlight lang="j"> require 'trig' |
|||
(sin , cos ,: tan) (1p1 % 4), rfd 45 |
|||
0.707107 0.707107 |
|||
0.707107 0.707107 |
|||
1 1 |
|||
([ ,. dfr) (arcsin , arccos ,: arctan) 0.5 |
|||
0.523599 30 |
|||
1.0472 60 |
|||
0.463648 26.5651</syntaxhighlight> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
Line 1,107: | Line 1,943: | ||
Java's <tt>Math</tt> 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 <tt>Math</tt> class also has a <tt>PI</tt> constant for easy conversion. |
Java's <tt>Math</tt> 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 <tt>Math</tt> class also has a <tt>PI</tt> constant for easy conversion. |
||
< |
<syntaxhighlight lang="java">public class Trig { |
||
public static void main(String[] args) { |
public static void main(String[] args) { |
||
//Pi / 4 is 45 degrees. All answers should be the same. |
//Pi / 4 is 45 degrees. All answers should be the same. |
||
Line 1,128: | Line 1,964: | ||
System.out.println(arctan + " " + Math.toDegrees(arctan)); |
System.out.println(arctan + " " + Math.toDegrees(arctan)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
0.7071067811865475 0.7071067811865475 |
0.7071067811865475 0.7071067811865475 |
||
Line 1,144: | Line 1,980: | ||
JavaScript's <tt>Math</tt> 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 <tt>Math</tt> class also has a <tt>PI</tt> constant for easy conversion. |
JavaScript's <tt>Math</tt> 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 <tt>Math</tt> class also has a <tt>PI</tt> constant for easy conversion. |
||
< |
<syntaxhighlight lang="javascript">var |
||
radians = Math.PI / 4, // Pi / 4 is 45 degrees. All answers should be the same. |
radians = Math.PI / 4, // Pi / 4 is 45 degrees. All answers should be the same. |
||
degrees = 45.0, |
degrees = 45.0, |
||
Line 1,165: | Line 2,001: | ||
window.alert(arccos + " " + (arccos * 180 / Math.PI)); |
window.alert(arccos + " " + (arccos * 180 / Math.PI)); |
||
// arctangent |
// arctangent |
||
window.alert(arctan + " " + (arctan * 180 / Math.PI));</ |
window.alert(arctan + " " + (arctan * 180 / Math.PI));</syntaxhighlight> |
||
=={{header|jq}}== |
|||
jq includes the standard C-library trigonometric functions (sin, cos, tan, asin, acos, atan), but they are provided as filters as illustrated in the definition of <tt>radians</tt> below. |
|||
The trigonometric filters only accept radians, so conversion is necessary when dealing with degrees. The constant <tt>π</tt> can be defined as also shown in the following definition of <tt>radians</tt>:<syntaxhighlight lang="jq"> |
|||
# degrees to radians |
|||
def radians: |
|||
(-1|acos) as $pi | (. * $pi / 180); |
|||
def task: |
|||
(-1|acos) as $pi |
|||
| ($pi / 180) as $degrees |
|||
| "Using radians:", |
|||
" sin(-pi / 6) = \( (-$pi / 6) | sin )", |
|||
" cos(3 * pi / 4) = \( (3 * $pi / 4) | cos)", |
|||
" tan(pi / 3) = \( ($pi / 3) | tan)", |
|||
" asin(-1 / 2) = \((-1 / 2) | asin)", |
|||
" acos(-sqrt(2)/2) = \((-(2|sqrt)/2) | acos )", |
|||
" atan(sqrt(3)) = \( 3 | sqrt | atan )", |
|||
"Using degrees:", |
|||
" sin(-30) = \((-30 * $degrees) | sin)", |
|||
" cos(135) = \((135 * $degrees) | cos)", |
|||
" tan(60) = \(( 60 * $degrees) | tan)", |
|||
" asin(-1 / 2) = \( (-1 / 2) | asin / $degrees)", |
|||
" acos(-sqrt(2)/2) = \( (-(2|sqrt) / 2) | acos / $degrees)", |
|||
" atan(sqrt(3)) = \( (3 | sqrt) | atan / $degrees)" |
|||
; |
|||
task |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<syntaxhighlight lang="sh">Using radians: |
|||
sin(-pi / 6) = -0.49999999999999994 |
|||
cos(3 * pi / 4) = -0.7071067811865475 |
|||
tan(pi / 3) = 1.7320508075688767 |
|||
asin(-1 / 2) = -0.5235987755982988 |
|||
acos(-sqrt(2)/2) = 2.356194490192345 |
|||
atan(sqrt(3)) = 1.0471975511965979 |
|||
Using degrees: |
|||
sin(-30) = -0.49999999999999994 |
|||
cos(135) = -0.7071067811865475 |
|||
tan(60) = 1.7320508075688767 |
|||
asin(-1 / 2) = -29.999999999999996 |
|||
acos(-sqrt(2)/2) = 135 |
|||
atan(sqrt(3)) = 60.00000000000001</syntaxhighlight> |
|||
=={{header|Jsish}}== |
|||
Like many programming languages that handle trig, Jsish also includes the ''atan2'' function, which was originally added to Fortran to allow disambiguous results when converting from cartesian to polar coordinates, due to the mirror image nature of normal arctan. |
|||
To find what methods are supported, ''jsish'' supports help for the Math module. |
|||
<pre>help Math |
|||
Math.method(...) |
|||
Commands performing math operations on numbers |
|||
Methods: abs acos asin atan atan2 ceil cos exp floor log max min pow random round sin sqrt tan</pre> |
|||
Angles passed to the trigonometric functions expect arguments in ''radians'' (Pi by 4 radians being 45 degrees). Degree to radian conversion is shown by multiplying radians by Pi over 180. |
|||
''Note the inexact nature of floating point approximations.'' |
|||
<syntaxhighlight lang="javascript">/* Trig in Jsish */ |
|||
var x; |
|||
;x = Math.PI / 4; |
|||
;Math.sin(x); |
|||
;Math.cos(x); |
|||
;Math.tan(x); |
|||
;Math.asin(Math.sin(x)) * 4; |
|||
;Math.acos(Math.cos(x)) * 4; |
|||
;Math.atan(Math.tan(x)); |
|||
;Math.atan2(Math.tan(x), 1.0); |
|||
;Math.atan2(Math.tan(x), -1.0); |
|||
;x = 45.0; |
|||
;Math.sin(x * Math.PI / 180); |
|||
;Math.cos(x * Math.PI / 180); |
|||
;Math.tan(x * Math.PI / 180); |
|||
/* |
|||
=!EXPECTSTART!= |
|||
x = Math.PI / 4 ==> 0.7853981633974483 |
|||
Math.sin(x) ==> 0.7071067811865475 |
|||
Math.cos(x) ==> 0.7071067811865476 |
|||
Math.tan(x) ==> 0.9999999999999999 |
|||
Math.asin(Math.sin(x)) * 4 ==> 3.141592653589793 |
|||
Math.acos(Math.cos(x)) * 4 ==> 3.141592653589793 |
|||
Math.atan(Math.tan(x)) ==> 0.7853981633974483 |
|||
Math.atan2(Math.tan(x), 1.0) ==> 0.7853981633974483 |
|||
Math.atan2(Math.tan(x), -1.0) ==> 2.356194490192345 |
|||
x = 45.0 ==> 45 |
|||
Math.sin(x * Math.PI / 180) ==> 0.7071067811865475 |
|||
Math.cos(x * Math.PI / 180) ==> 0.7071067811865476 |
|||
Math.tan(x * Math.PI / 180) ==> 0.9999999999999999 |
|||
=!EXPECTEND!= |
|||
*/</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ jsish --U trigonometric.jsi |
|||
x = Math.PI / 4 ==> 0.7853981633974483 |
|||
Math.sin(x) ==> 0.7071067811865475 |
|||
Math.cos(x) ==> 0.7071067811865476 |
|||
Math.tan(x) ==> 0.9999999999999999 |
|||
Math.asin(Math.sin(x)) * 4 ==> 3.141592653589793 |
|||
Math.acos(Math.cos(x)) * 4 ==> 3.141592653589793 |
|||
Math.atan(Math.tan(x)) ==> 0.7853981633974483 |
|||
Math.atan2(Math.tan(x), 1.0) ==> 0.7853981633974483 |
|||
Math.atan2(Math.tan(x), -1.0) ==> 2.356194490192345 |
|||
x = 45.0 ==> 45 |
|||
Math.sin(x * Math.PI / 180) ==> 0.7071067811865475 |
|||
Math.cos(x * Math.PI / 180) ==> 0.7071067811865476 |
|||
Math.tan(x * Math.PI / 180) ==> 0.9999999999999999 |
|||
prompt$ jsish -u trigonometric.jsi |
|||
[PASS] trigonometric.jsi</pre> |
|||
=={{header|Julia}}== |
|||
<syntaxhighlight lang="julia"># v0.6.0 |
|||
rad = π / 4 |
|||
deg = 45.0 |
|||
@show rad deg |
|||
@show sin(rad) sin(deg2rad(deg)) |
|||
@show cos(rad) cos(deg2rad(deg)) |
|||
@show tan(rad) tan(deg2rad(deg)) |
|||
@show asin(sin(rad)) asin(sin(rad)) |> rad2deg |
|||
@show acos(cos(rad)) acos(cos(rad)) |> rad2deg |
|||
@show atan(tan(rad)) atan(tan(rad)) |> rad2deg</syntaxhighlight> |
|||
{{out}} |
|||
<pre>rad = 0.7853981633974483 |
|||
deg = 45.0 |
|||
sin(rad) = 0.7071067811865475 |
|||
sin(deg2rad(deg)) = 0.7071067811865475 |
|||
cos(rad) = 0.7071067811865476 |
|||
cos(deg2rad(deg)) = 0.7071067811865476 |
|||
tan(rad) = 0.9999999999999999 |
|||
tan(deg2rad(deg)) = 0.9999999999999999 |
|||
asin(sin(rad)) = 0.7853981633974482 |
|||
asin(sin(rad)) |> rad2deg = 44.99999999999999 |
|||
acos(cos(rad)) = 0.7853981633974483 |
|||
acos(cos(rad)) |> rad2deg = 45.0 |
|||
atan(tan(rad)) = 0.7853981633974483 |
|||
atan(tan(rad)) |> rad2deg = 45.0</pre> |
|||
=={{header|Kotlin}}== |
|||
<syntaxhighlight lang="kotlin">import kotlin.math.* |
|||
fun main() { |
|||
fun Double.toDegrees() = this * 180 / PI |
|||
val angle = PI / 4 |
|||
println("angle = $angle rad = ${angle.toDegrees()}°") |
|||
val sine = sin(angle) |
|||
println("sin(angle) = $sine") |
|||
val cosine = cos(angle) |
|||
println("cos(angle) = $cosine") |
|||
val tangent = tan(angle) |
|||
println("tan(angle) = $tangent") |
|||
println() |
|||
val asin = asin(sine) |
|||
println("asin(sin(angle)) = $asin rad = ${asin.toDegrees()}°") |
|||
val acos = acos(cosine) |
|||
println("acos(cos(angle)) = $acos rad = ${acos.toDegrees()}°") |
|||
val atan = atan(tangent) |
|||
println("atan(tan(angle)) = $atan rad = ${atan.toDegrees()}°") |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
angle = 0.7853981633974483 rad = 45.0° |
|||
sin(angle) = 0.7071067811865475 |
|||
cos(angle) = 0.7071067811865476 |
|||
tan(angle) = 0.9999999999999999 |
|||
asin(sin(angle)) = 0.7853981633974482 rad = 44.99999999999999° |
|||
acos(cos(angle)) = 0.7853981633974483 rad = 45.0° |
|||
atan(tan(angle)) = 0.7853981633974483 rad = 45.0° |
|||
</pre> |
|||
=={{header|Lambdatalk}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
{def deg2rad {lambda {:d} {* {/ {PI} 180} :d}}} |
|||
-> deg2rad |
|||
{def rad2deg {lambda {:r} {* {/ 180 {PI}} :r}}} |
|||
-> rad2deg |
|||
{deg2rad 180} |
|||
-> 3.141592653589793 = PI |
|||
{rad2deg {PI}}° |
|||
-> 180° |
|||
{sin {deg2rad 45}} |
|||
-> 0.7071067811865475 = PI/4 |
|||
{cos {deg2rad 45}} |
|||
-> 0.7071067811865476 = PI/4 |
|||
{tan {deg2rad 45}} |
|||
-> 0.9999999999999999 = 1 |
|||
{rad2deg {asin 0.5}}° -> 30.000000000000004° |
|||
{rad2deg {acos 0.5}}° -> 60.00000000000001° |
|||
{rad2deg {atan 1}}° -> 45° |
|||
</syntaxhighlight> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">pi = ACS(-1) |
||
radians = pi / 4.0 |
radians = pi / 4.0 |
||
rtod = 180 / pi |
rtod = 180 / pi |
||
Line 1,181: | Line 2,223: | ||
print "Asn: ";ASN(SIN(radians));" Rad, "; ASN(SIN(degrees*dtor))*rtod;" Deg" |
print "Asn: ";ASN(SIN(radians));" Rad, "; ASN(SIN(degrees*dtor))*rtod;" Deg" |
||
print "Acs: ";ACS(COS(radians));" Rad, "; ACS(COS(degrees*dtor))*rtod;" Deg" |
print "Acs: ";ACS(COS(radians));" Rad, "; ACS(COS(degrees*dtor))*rtod;" Deg" |
||
print "Atn: ";ATN(TAN(radians));" Rad, "; ATN(TAN(degrees*dtor))*rtod;" Deg"</ |
print "Atn: ";ATN(TAN(radians));" Rad, "; ATN(TAN(degrees*dtor))*rtod;" Deg"</syntaxhighlight> |
||
{{out}} |
|||
<pre>Sin: 0.70710678 0.70710678 |
<pre>Sin: 0.70710678 0.70710678 |
||
Cos: 0.70710678 0.70710678 |
Cos: 0.70710678 0.70710678 |
||
Line 1,192: | Line 2,235: | ||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
[[UCB Logo]] has sine, cosine, and arctangent; each having variants for degrees or radians. |
[[UCB Logo]] has sine, cosine, and arctangent; each having variants for degrees or radians. |
||
< |
<syntaxhighlight lang="logo">print sin 45 |
||
print cos 45 |
print cos 45 |
||
print arctan 1 |
print arctan 1 |
||
Line 1,198: | Line 2,241: | ||
print radsin :pi / 4 |
print radsin :pi / 4 |
||
print radcos :pi / 4 |
print radcos :pi / 4 |
||
print 4 * radarctan 1</ |
print 4 * radarctan 1</syntaxhighlight> |
||
[[Lhogho]] has pi defined in its trigonometric functions. Otherwise the same as UCB Logo. |
[[Lhogho]] has pi defined in its trigonometric functions. Otherwise the same as UCB Logo. |
||
< |
<syntaxhighlight lang="logo">print sin 45 |
||
print cos 45 |
print cos 45 |
||
print arctan 1 |
print arctan 1 |
||
print radsin pi / 4 |
print radsin pi / 4 |
||
print radcos pi / 4 |
print radcos pi / 4 |
||
print 4 * radarctan 1</ |
print 4 * radarctan 1</syntaxhighlight> |
||
=={{header|Logtalk}}== |
|||
<syntaxhighlight lang="logtalk"> |
|||
:- object(trignomeric_functions). |
|||
:- public(show/0). |
|||
show :- |
|||
% standard trignomeric functions work with radians |
|||
write('sin(pi/4.0) = '), SIN is sin(pi/4.0), write(SIN), nl, |
|||
write('cos(pi/4.0) = '), COS is cos(pi/4.0), write(COS), nl, |
|||
write('tan(pi/4.0) = '), TAN is tan(pi/4.0), write(TAN), nl, |
|||
write('asin(sin(pi/4.0)) = '), ASIN is asin(sin(pi/4.0)), write(ASIN), nl, |
|||
write('acos(cos(pi/4.0)) = '), ACOS is acos(cos(pi/4.0)), write(ACOS), nl, |
|||
write('atan(tan(pi/4.0)) = '), ATAN is atan(tan(pi/4.0)), write(ATAN), nl, |
|||
write('atan2(3,4) = '), ATAN2 is atan2(3,4), write(ATAN2), nl. |
|||
:- end_object. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<syntaxhighlight lang="text"> |
|||
?- trignomeric_functions::show. |
|||
sin(pi/4.0) = 0.7071067811865475 |
|||
cos(pi/4.0) = 0.7071067811865476 |
|||
tan(pi/4.0) = 0.9999999999999999 |
|||
asin(sin(pi/4.0)) = 0.7853981633974482 |
|||
acos(cos(pi/4.0)) = 0.7853981633974483 |
|||
atan(tan(pi/4.0)) = 0.7853981633974483 |
|||
atan2(3,4) = 0.6435011087932844 |
|||
yes |
|||
</syntaxhighlight> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4))</syntaxhighlight> |
||
=={{header|Maple}}== |
|||
In radians: |
|||
<syntaxhighlight lang="maple">sin(Pi/3); |
|||
cos(Pi/3); |
|||
tan(Pi/3);</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
> sin(Pi/3); |
|||
1/2 |
|||
3 |
|||
---- |
|||
2 |
|||
> cos(Pi/3); |
|||
1/2 |
|||
> tan(Pi/3); |
|||
1/2 |
|||
3 |
|||
</pre> |
|||
The equivalent in degrees with identical output: |
|||
<syntaxhighlight lang="maple">with(Units[Standard]): |
|||
sin(60*Unit(degree)); |
|||
cos(60*Unit(degree)); |
|||
tan(60*Unit(degree));</syntaxhighlight> |
|||
Note, Maple also has secant, cosecant, and cotangent: |
|||
<syntaxhighlight lang="maple">csc(Pi/3); |
|||
sec(Pi/3); |
|||
cot(Pi/3);</syntaxhighlight> |
|||
Finally, the inverse trigonometric functions: |
|||
<syntaxhighlight lang="maple">arcsin(1); |
|||
arccos(1); |
|||
arctan(1);</syntaxhighlight> |
|||
{{out}} |
|||
<pre>> arcsin(1); |
|||
Pi |
|||
---- |
|||
2 |
|||
> arccos(1); |
|||
0 |
|||
> arctan(1); |
|||
Pi |
|||
---- |
|||
4 |
|||
</pre> |
|||
Lastly, Maple also supports the two-argument arctan plus all the hyperbolic trigonometric functions. |
|||
=={{header|Mathematica}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">Sin[1] |
||
Cos[1] |
Cos[1] |
||
Tan[1] |
Tan[1] |
||
Line 1,221: | Line 2,346: | ||
Sin[90 Degree] |
Sin[90 Degree] |
||
Cos[90 Degree] |
Cos[90 Degree] |
||
Tan[90 Degree] |
Tan[90 Degree]</syntaxhighlight> |
||
</lang> |
|||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
A full list of built-in trig functions can be found in the [http://www.mathworks.com/access/helpdesk/help/techdoc/ref/f16-5872.html#f16-6197 MATLAB Documentation]. |
A full list of built-in trig functions can be found in the [http://www.mathworks.com/access/helpdesk/help/techdoc/ref/f16-5872.html#f16-6197 MATLAB Documentation]. |
||
< |
<syntaxhighlight lang="matlab">function trigExample(angleDegrees) |
||
angleRadians = angleDegrees * (pi/180); |
angleRadians = angleDegrees * (pi/180); |
||
Line 1,239: | Line 2,363: | ||
disp(sprintf('tan(%f)= %f\natan(%f)= %f',[angleRadians tan(angleRadians) tan(angleRadians) atan(tan(angleRadians))])); |
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))])); |
disp(sprintf('tand(%f)= %f\narctand(%f)= %f',[angleDegrees tand(angleDegrees) tand(angleDegrees) atand(tand(angleDegrees))])); |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
|||
Sample Output: |
|||
< |
<syntaxhighlight lang="matlab">>> trigExample(78) |
||
sin(1.361357)= 0.978148 |
sin(1.361357)= 0.978148 |
||
asin(0.978148)= 1.361357 |
asin(0.978148)= 1.361357 |
||
Line 1,256: | Line 2,380: | ||
atan(4.704630)= 1.361357 |
atan(4.704630)= 1.361357 |
||
tand(78.000000)= 4.704630 |
tand(78.000000)= 4.704630 |
||
arctand(4.704630)= 78.000000</ |
arctand(4.704630)= 78.000000</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">a: %pi / 3; |
||
[sin(a), cos(a), tan(a), sec(a), csc(a), cot(a)]; |
[sin(a), cos(a), tan(a), sec(a), csc(a), cot(a)]; |
||
Line 1,268: | Line 2,392: | ||
a: 1 / 2; |
a: 1 / 2; |
||
[sinh(a), cosh(a), tanh(a), sech(a), csch(a), coth(a)], numer; |
[sinh(a), cosh(a), tanh(a), sech(a), csch(a), coth(a)], numer; |
||
[asinh(a), acosh(1 / a), atanh(a), asech(a), acsch(a), acoth(1 / a)], numer;</ |
[asinh(a), acosh(1 / a), atanh(a), asech(a), acsch(a), acoth(1 / a)], numer;</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
Maxscript trigonometric functions accept degrees only. The built-ins degToRad and radToDeg allow easy conversion. |
Maxscript trigonometric functions accept degrees only. The built-ins degToRad and radToDeg allow easy conversion. |
||
< |
<syntaxhighlight lang="maxscript">local radians = pi / 4 |
||
local degrees = 45.0 |
local degrees = 45.0 |
||
Line 1,292: | Line 2,416: | ||
--arctangent |
--arctangent |
||
print (atan (tan (radToDeg radians))) |
print (atan (tan (radToDeg radians))) |
||
print (atan (tan degrees))</ |
print (atan (tan degrees))</syntaxhighlight> |
||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
Line 1,298: | Line 2,422: | ||
Metafont has <code>sind</code> and <code>cosd</code>, which compute sine and cosine of an angle expressed in degree. We need to define the rest. |
Metafont has <code>sind</code> and <code>cosd</code>, which compute sine and cosine of an angle expressed in degree. We need to define the rest. |
||
< |
<syntaxhighlight lang="metafont">Pi := 3.14159; |
||
vardef torad expr x = Pi*x/180 enddef; % conversions |
vardef torad expr x = Pi*x/180 enddef; % conversions |
||
vardef todeg expr x = 180x/Pi enddef; |
vardef todeg expr x = 180x/Pi enddef; |
||
Line 1,343: | Line 2,467: | ||
outcompare(tan(Pi/3), tand(60)); |
outcompare(tan(Pi/3), tand(60)); |
||
end</ |
end</syntaxhighlight> |
||
=={{header|MiniScript}}== |
|||
<syntaxhighlight lang="miniscript">pi3 = pi/3 |
|||
degToRad = pi/180 |
|||
print "sin PI/3 radians = " + sin(pi3) |
|||
print "sin 60 degrees = " + sin(60*degToRad) |
|||
print "arcsin 0.5 in radians = " + asin(0.5) |
|||
print "arcsin 0.5 in degrees = " + asin(0.5)/degToRad |
|||
print "cos PI/3 radians = " + cos(pi3) |
|||
print "cos 60 degrees = " + cos(60*degToRad) |
|||
print "arccos 0.5 in radians = " + acos(0.5) |
|||
print "arccos 0.5 in degrees = " + acos(0.5)/degToRad |
|||
print "tan PI/3 radians = " + tan(pi3) |
|||
print "tan 60 degrees = " + tan(60*degToRad) |
|||
print "arctan 0.5 in radians = " + atan(0.5) |
|||
print "arctan 0.5 in degrees = " + atan(0.5)/degToRad</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
sin PI/3 radians = 0.866025 |
|||
sin 60 degrees = 0.866025 |
|||
arcsin 0.5 in radians = 0.523599 |
|||
arcsin 0.5 in degrees = 30.0 |
|||
cos PI/3 radians = 0.5 |
|||
cos 60 degrees = 0.5 |
|||
arccos 0.5 in radians = 1.047198 |
|||
arccos 0.5 in degrees = 60.0 |
|||
tan PI/3 radians = 1.732051 |
|||
tan 60 degrees = 1.732051 |
|||
arctan 0.5 in radians = 0.463648 |
|||
arctan 0.5 in degrees = 26.565051 |
|||
</pre> |
|||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
Line 1,352: | Line 2,507: | ||
Setting the units of angle (degrees, radians, grads) takes care of the switch ''Р-ГРД-Г''. |
Setting the units of angle (degrees, radians, grads) takes care of the switch ''Р-ГРД-Г''. |
||
=={{header|Modula-2}}== |
|||
<syntaxhighlight lang="modula2">MODULE Trig; |
|||
FROM RealMath IMPORT pi,sin,cos,tan,arctan,arccos,arcsin; |
|||
FROM RealStr IMPORT RealToStr; |
|||
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
|||
PROCEDURE WriteReal(v : REAL); |
|||
VAR buf : ARRAY[0..31] OF CHAR; |
|||
BEGIN |
|||
RealToStr(v, buf); |
|||
WriteString(buf) |
|||
END WriteReal; |
|||
VAR theta : REAL; |
|||
BEGIN |
|||
theta := pi / 4.0; |
|||
WriteString("theta: "); |
|||
WriteReal(theta); |
|||
WriteLn; |
|||
WriteString("sin: "); |
|||
WriteReal(sin(theta)); |
|||
WriteLn; |
|||
WriteString("cos: "); |
|||
WriteReal(cos(theta)); |
|||
WriteLn; |
|||
WriteString("tan: "); |
|||
WriteReal(tan(theta)); |
|||
WriteLn; |
|||
WriteString("arcsin: "); |
|||
WriteReal(arcsin(sin(theta))); |
|||
WriteLn; |
|||
WriteString("arccos: "); |
|||
WriteReal(arccos(cos(theta))); |
|||
WriteLn; |
|||
WriteString("arctan: "); |
|||
WriteReal(arctan(tan(theta))); |
|||
WriteLn; |
|||
ReadChar |
|||
END Trig.</syntaxhighlight> |
|||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary utf8 |
options replace format comments java crossref symbols nobinary utf8 |
||
Line 1,389: | Line 2,592: | ||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
|||
'''Output:''' |
|||
<pre> |
<pre> |
||
| Radians | Degrees | |
| Radians | Degrees | |
||
Line 1,402: | Line 2,605: | ||
arctangent| 0.785398163397 | 45.000000000000 | |
arctangent| 0.785398163397 | 45.000000000000 | |
||
</pre> |
</pre> |
||
=={{header|Nim}}== |
|||
<syntaxhighlight lang="nim">import math, strformat |
|||
let rad = Pi/4 |
|||
let deg = 45.0 |
|||
echo &"Sine: {sin(rad):.10f} {sin(degToRad(deg)):13.10f}" |
|||
echo &"Cosine : {cos(rad):.10f} {cos(degToRad(deg)):13.10f}" |
|||
echo &"Tangent: {tan(rad):.10f} {tan(degToRad(deg)):13.10f}" |
|||
echo &"Arcsine: {arcsin(sin(rad)):.10f} {radToDeg(arcsin(sin(degToRad(deg)))):13.10f}" |
|||
echo &"Arccosine: {arccos(cos(rad)):.10f} {radToDeg(arccos(cos(degToRad(deg)))):13.10f}" |
|||
echo &"Arctangent: {arctan(tan(rad)):.10f} {radToDeg(arctan(tan(degToRad(deg)))):13.10f}" |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Sine: 0.7071067812 0.7071067812 |
|||
Cosine : 0.7071067812 0.7071067812 |
|||
Tangent: 1.0000000000 1.0000000000 |
|||
Arcsine: 0.7853981634 45.0000000000 |
|||
Arccosine: 0.7853981634 45.0000000000 |
|||
Arctangent: 0.7853981634 45.0000000000</pre> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
OCaml's preloaded <tt>Pervasives</tt> module contains all six functions. The functions all accept radians only, so conversion is necessary when dealing with degrees. |
OCaml's preloaded <tt>Pervasives</tt> module contains all six functions. The functions all accept radians only, so conversion is necessary when dealing with degrees. |
||
< |
<syntaxhighlight lang="ocaml">let pi = 4. *. atan 1. |
||
let radians = pi /. 4. |
let radians = pi /. 4. |
||
Line 1,419: | Line 2,644: | ||
Printf.printf "%f %f\n" arccos (arccos *. 180. /. pi);; |
Printf.printf "%f %f\n" arccos (arccos *. 180. /. pi);; |
||
let arctan = atan (tan radians);; |
let arctan = atan (tan radians);; |
||
Printf.printf "%f %f\n" arctan (arctan *. 180. /. pi);;</ |
Printf.printf "%f %f\n" arctan (arctan *. 180. /. pi);;</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
0.707107 0.707107 |
0.707107 0.707107 |
||
Line 1,432: | Line 2,657: | ||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">function d = degree(rad) |
||
d = 180*rad/pi; |
d = 180*rad/pi; |
||
endfunction |
endfunction |
||
Line 1,452: | Line 2,677: | ||
ifuncs{i}, v, iv, |
ifuncs{i}, v, iv, |
||
strcat(ifuncs{i}, "d"), vd, ivd); |
strcat(ifuncs{i}, "d"), vd, ivd); |
||
endfor</ |
endfor</syntaxhighlight> |
||
Output: |
|||
{{out}} |
|||
<pre>sin(1.047198) = sind(60.000000) = 0.866025 (0.866025) |
<pre>sin(1.047198) = sind(60.000000) = 0.866025 (0.866025) |
||
asin(0.866025) = 1.047198 |
asin(0.866025) = 1.047198 |
||
Line 1,476: | Line 2,700: | ||
(Lacking in this code but present in GNU Octave: sinh, cosh, tanh, coth and inverses) |
(Lacking in this code but present in GNU Octave: sinh, cosh, tanh, coth and inverses) |
||
=={{header|Oforth}}== |
|||
<syntaxhighlight lang="oforth">import: math |
|||
: testTrigo |
|||
| rad deg hyp z | |
|||
Pi 4 / ->rad |
|||
45.0 ->deg |
|||
0.5 ->hyp |
|||
System.Out rad sin << " - " << deg asRadian sin << cr |
|||
System.Out rad cos << " - " << deg asRadian cos << cr |
|||
System.Out rad tan << " - " << deg asRadian tan << cr |
|||
printcr |
|||
rad sin asin ->z |
|||
System.Out z << " - " << z asDegree << cr |
|||
rad cos acos ->z |
|||
System.Out z << " - " << z asDegree << cr |
|||
rad tan atan ->z |
|||
System.Out z << " - " << z asDegree << cr |
|||
printcr |
|||
System.Out hyp sinh << " - " << hyp sinh asinh << cr |
|||
System.Out hyp cosh << " - " << hyp cosh acosh << cr |
|||
System.Out hyp tanh << " - " << hyp tanh atanh << cr ;</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0.707106781186547 - 0.707106781186547 |
|||
0.707106781186548 - 0.707106781186548 |
|||
1 - 1 |
|||
0.785398163397448 - 45 |
|||
0.785398163397448 - 45 |
|||
0.785398163397448 - 45 |
|||
0.521095305493747 - 0.5 |
|||
1.12762596520638 - 0.5 |
|||
0.46211715726001 - 0.5 |
|||
</pre> |
|||
=={{header|ooRexx}}== |
|||
<pre> |
|||
rxm.cls 20 March 2014 |
|||
The distribution of ooRexx contains a function package called rxMath |
|||
that provides the computation of trigonometric and some other functions. |
|||
Based on the underlying C-library the precision of the returned values |
|||
is limited to 16 digits. Close observation show that sometimes the last |
|||
one to three digits of the returned values are not correct. |
|||
Many years ago I experimented with implementing these functions in Rexx |
|||
with its virtually unlimited precision. |
|||
The rxm class is intended to provide the same functionality as rxMath |
|||
with no limit on the specified or implied precision. |
|||
Functions in class rxm and invocation syntax are the same as |
|||
in the rxMath library. They are implemented as routines which |
|||
perform the checking of argument values and invoke the corresponding |
|||
methods. Here is a list of the supported functions and a concise |
|||
syntax specification. |
|||
The arguments are represented by these letters: |
|||
x is the value for which the respective function must be evaluated. |
|||
b and c for RxCalcPower are base and exponent, respectively. |
|||
p if specified is the desired precision (number of digits) in the result. |
|||
It can be any integer from 1 to 999999. |
|||
See below for the default used. |
|||
u if specified, is the unit of x given to the trigonometric functions |
|||
or the unit of the value returned by the Arcus functions. |
|||
It can be 'R', 'D', or 'G' for radians, degrees, or grades, respectively. |
|||
See below for the default used. |
|||
Trigonometric functions: |
|||
• rxmCos(x[,[p][,u]]) |
|||
• rxmCotan(x[,[p][,u]]) |
|||
• rxmSin(x[,[p][,u]]) |
|||
• rxmTan(x[,[p][,u]]) |
|||
Arcus functions: |
|||
• rxmArcCos(x[,[p][,u]]) |
|||
• rxmArcSin(x[,[p][,u]]) |
|||
• rxmArcTan(x[,[p][,u]]) |
|||
Hyperbolic functions: |
|||
• rxmCosH(x[,p]) |
|||
• rxmSinH(x[,p]) |
|||
• rxmTanH(x[,p]) |
|||
• rxmExp(x[,p]) e**x |
|||
• rxmLog(x[,p]) Natural logarithm of x |
|||
• rxmLog10(x[,p]) Brigg's logarithm of x |
|||
• rxmSqrt(x[,p]) Square root of x |
|||
• rxmPower(b,c[,p]) b**c |
|||
• rxmPi([p]) pi to the specified or default precision |
|||
Values used for p and u if these are omitted in the invocation |
|||
============================================================== |
|||
The directive ::REQUIRES rxm.cls creates an instance of the class |
|||
.local~my.rxm=.rxm~new(16,"D") |
|||
which sets the defaults for p=16 and u='D'. |
|||
These are used when p or u are omitted in a function invocation. |
|||
They can be changed by changing the respective class attributes as follows: |
|||
.locaL~my.rxm~precision=50 |
|||
.locaL~my.rxm~type='R' |
|||
The current setting of these attributes can be retrieved as follows: |
|||
.locaL~my.rxm~precision() |
|||
.locaL~my.rxm~type() |
|||
While I tried to get full compatibility there remain a few |
|||
(actually very few) differences: |
|||
rxCalcTan(90) raises the Syntax condition (will be fixed in the next ooRexx release) |
|||
rxCalcexp(x) limits x to 709. or so and returns '+infinity' for larger exponents |
|||
</pre> |
|||
<syntaxhighlight lang="oorexx">/* REXX --------------------------------------------------------------- |
|||
* show how the functions can be used |
|||
* 03.05.2014 Walter Pachl |
|||
*--------------------------------------------------------------------*/ |
|||
Say 'Default precision:' .locaL~my.rxm~precision() |
|||
Say 'Default type: ' .locaL~my.rxm~type() |
|||
Say 'rxmsin(60) ='rxmsin(60) -- use default precision and type |
|||
Say 'rxmsin(1,21,"R")='rxmsin(1,21,'R') -- precision and type specified |
|||
Say 'rxmlog(-1) ='rxmlog(-1) |
|||
Say 'rxmlog( 0) ='rxmlog( 0) |
|||
Say 'rxmlog( 1) ='rxmlog( 1) |
|||
Say 'rxmlog( 2) ='rxmlog( 2) |
|||
.locaL~my.rxm~precision=50 |
|||
.locaL~my.rxm~type='R' |
|||
Say 'Changed precision:' .locaL~my.rxm~precision() |
|||
Say 'Changed type: ' .locaL~my.rxm~type() |
|||
Say 'rxmsin(1) ='rxmsin(1) -- use changed precision and type |
|||
::requires rxm.cls</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Default precision: 16 |
|||
Default type: D |
|||
rxmsin(60) =0.8660254037844386 |
|||
rxmsin(1,21,"R")=0.841470984807896506653 |
|||
rxmlog(-1) =nan |
|||
rxmlog( 0) =-infinity |
|||
rxmlog( 1) =0 |
|||
rxmlog( 2) =0.6931471805599453 |
|||
Changed precision: 50 |
|||
Changed type: R |
|||
rxmsin(1) =0.84147098480789650665250232163029899962256306079837</pre> |
|||
<syntaxhighlight lang="oorexx">/******************************************************************** |
|||
* Package rxm |
|||
* implements the functions available in RxMath with high precision |
|||
* by computing the values with significantly increased precision |
|||
* and rounding the result to the specified precision. |
|||
* This started 10 years ago when Vladimir Zabrodsky published his |
|||
* Album of Algorithms http://zabrodsky-rexx.byethost18.com/aat/ |
|||
* Gerard Schildberger suggests on rosettacode.org to use +10 digits |
|||
* Rony Flatscher suggested and helped to turn this into an ooRexx class |
|||
* Rick McGuire advised on using Use STRICT Arg for argument checking |
|||
* Alexander Seik creates this documentation |
|||
* Horst Wegscheider helped with reviewing and some improvements |
|||
* 12.04.2014 Walter Pachl |
|||
* Documentation: see rxmath.pdf in the ooRexx distribution |
|||
* and rxm.doc (here) |
|||
* 13.04.2014 WP arcsin and arctan commentary corrected (courtesy Horst) |
|||
* 13.04.2014 WP improve arctan performance |
|||
* 20.04.2014 WP towards completion |
|||
* 24.04.2014 WP arcsin verbessert. courtesy Horst Wegscheider |
|||
* 28.04.2014 WP run ooRexxDoc |
|||
* 11.08.2014 WP replace log algorithm with Vladimir Zabrodsky's code |
|||
**********************************************************************/ |
|||
.local~my.rxm=.rxm~new(16,"D") |
|||
::Class rxm Public |
|||
::Method init |
|||
Expose precision type |
|||
Use Arg precision=(digits()),type='D' |
|||
::attribute precision set |
|||
Expose precision |
|||
Use Strict Arg precision=(digits()) |
|||
::attribute precision get |
|||
::attribute type set |
|||
Expose type |
|||
Use Strict Arg type='R' |
|||
::attribute type get |
|||
::Method arccos |
|||
/*********************************************************************** |
|||
* Return arccos(x,precision,type) -- with specified precision |
|||
* arccos(x) = pi/2 - arcsin(x) |
|||
***********************************************************************/ |
|||
Expose precision type |
|||
Use Strict Arg x,xprec=(precision),xtype=(type) |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
If x=1 Then |
|||
r=0 |
|||
Else Do |
|||
r=self~arcsin(x,iprec,'R') |
|||
If r='nan' Then |
|||
Return r |
|||
r=self~pi(iprec)/2 - r |
|||
End |
|||
Select |
|||
When xtype='D' Then |
|||
r=r*180/self~pi(iprec) |
|||
When xtype='G' Then |
|||
r=r*200/self~pi(iprec) |
|||
Otherwise |
|||
Nop |
|||
End |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::Method arcsin |
|||
/*********************************************************************** |
|||
* Return arcsin(x,precision,type) -- with specified precision |
|||
* arcsin(x) = x+(x**3)*1/2*3+(x**5)*1*3/2*4*5+(x**7)*1*3*5/2*4*6*7+... |
|||
***********************************************************************/ |
|||
Expose precision type |
|||
Use Strict Arg x,xprec=(precision),xtype=(type) |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
sign=sign(x) |
|||
If x<0 Then |
|||
x=abs(x) |
|||
Select |
|||
When abs(x)>1 Then |
|||
Return 'nan' |
|||
When x=0 Then |
|||
r=0 |
|||
When x=1 Then |
|||
r=rxmpi(iprec)/2 |
|||
When x<0.8 Then Do |
|||
o=x |
|||
u=1 |
|||
r=x |
|||
Do i=3 By 2 Until ra=r |
|||
ra=r |
|||
o=o*x*x*(i-2) |
|||
u=u*(i-1)*i/(i-2) |
|||
r=r+(o/u) |
|||
If r=ra Then |
|||
r=r+(o/u)/2 /* final touch */ |
|||
End |
|||
End |
|||
Otherwise Do |
|||
z=x |
|||
r=x |
|||
o=x |
|||
s=x*x |
|||
do j=2 by 2; |
|||
o=o*s*(j-1)/j; |
|||
z=z+o/(j+1); |
|||
if z=r then |
|||
leave |
|||
r=z; |
|||
end |
|||
/*********************** |
|||
y=(1-x*x)/4 |
|||
n=0.5-self~sqrt(y,iprec) |
|||
z=self~sqrt(n,iprec) |
|||
r=2*self~arcsin(z,xprec) |
|||
***********************/ |
|||
End |
|||
End |
|||
Select |
|||
When xtype='D' Then |
|||
r=r*180/self~pi(iprec) |
|||
When xtype='G' Then |
|||
r=r*200/self~pi(iprec) |
|||
Otherwise |
|||
Nop |
|||
End |
|||
Numeric Digits xprec |
|||
Return sign*(r+0) |
|||
::Method arctan |
|||
/*********************************************************************** |
|||
* Return arctan(x,precision,type) -- with specified precision |
|||
* x=0 -> arctan(x) = 0 |
|||
* If x>0 Then |
|||
* x<1 -> arctan(x) = arcsin(x/sqrt(x**2+1)) |
|||
* x=1 -> arctan(x) = pi/4 |
|||
* x>1 -> arctan(x) = pi/2-arcsin((1/x)/sqrt((1/x)**2+1)) |
|||
* Else |
|||
* adjust as necessary |
|||
***********************************************************************/ |
|||
Expose precision type |
|||
Use Strict Arg x,xprec=(precision),xtype=(type) |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
Select |
|||
When abs(x)<1 Then |
|||
r=self~arcsin(x/self~sqrt(1+x**2,iprec),iprec,'R') |
|||
When abs(x)=1 Then |
|||
r=self~pi(iprec)/4*sign(x) |
|||
Otherwise Do |
|||
xr=1/abs(x) |
|||
r=self~arcsin(xr/self~sqrt(1+xr**2,iprec),iprec,'R') |
|||
If x>0 Then |
|||
r=self~pi(iprec)/2-r |
|||
Else |
|||
r=-self~pi(iprec)/2+r |
|||
End |
|||
End |
|||
Select |
|||
When xtype='D' Then |
|||
r=r*180/self~pi(iprec) |
|||
When xtype='G' Then |
|||
r=r*200/self~pi(iprec) |
|||
Otherwise |
|||
Nop |
|||
End |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::Method arsinh |
|||
/*********************************************************************** |
|||
* Return arsinh(x,precision,type) -- with specified precision |
|||
* arsinh(x) = ln(x+sqrt(x**2+1)) |
|||
***********************************************************************/ |
|||
Expose precision |
|||
Use Strict Arg x,xprec=(precision) |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
x2p1=x**2+1 |
|||
r=self~log(x+self~sqrt(x2p1,iprec),iprec) |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::Method cos |
|||
/* REXX ************************************************************* |
|||
* Return cos(x,precision,type) -- with the specified precision |
|||
* cos(x)=sin(x+pi/2) |
|||
********************************************************************/ |
|||
Expose precision type |
|||
Use Strict Arg x,xprec=(precision),xtype=(type) |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
Select |
|||
When xtype='R' Then xa=x+self~pi(iprec)/2 |
|||
When xtype='D' Then xa=x+90 |
|||
When xtype='G' Then xa=x+100 |
|||
End |
|||
r=self~sin(xa,iprec,xtype) |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::Method cosh |
|||
/* REXX **************************************************************** |
|||
* Return cosh(x,precision,type) -- with specified precision |
|||
* cosh(x) = 1+(x**2/2!)+(x**4/4!)+(x**6/6!)+-... |
|||
***********************************************************************/ |
|||
Expose precision |
|||
Use Strict Arg x,xprec=(precision) |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
o=1 |
|||
u=1 |
|||
r=1 |
|||
Do i=2 By 2 Until ra=r |
|||
ra=r |
|||
o=o*x*x |
|||
u=u*i*(i-1) |
|||
r=r+(o/u) |
|||
End |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::Method cotan |
|||
/* REXX ************************************************************* |
|||
* Return cotan(x,precision,type) -- with the specified precision |
|||
* cot(x)=cos(x)/sin(x) |
|||
********************************************************************/ |
|||
Expose precision type |
|||
Use Strict Arg x,xprec=(precision),xtype=(type) |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
s=self~sin(x,iprec,xtype) |
|||
c=self~cos(x,iprec,xtype) |
|||
If s=0 Then |
|||
Return '+infinity' |
|||
r=c/s |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::Method exp |
|||
/*********************************************************************** |
|||
* exp(x,precision) returns e**x -- with specified precision |
|||
* exp(x,precision,base) returns base**x -- with specified precision |
|||
***********************************************************************/ |
|||
Expose precision |
|||
Use Strict Arg x,xprec=(precision),xbase='' |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
Numeric Fuzz 3 |
|||
If xbase<>'' Then Do |
|||
Select |
|||
When xbase=0 Then Do |
|||
Select |
|||
When x<0 Then Return '+infinity' |
|||
When x=0 Then Return 'nan' |
|||
Otherwise Return 0 |
|||
End |
|||
End |
|||
When xbase=1 Then Return 1 |
|||
When xbase<0 Then Do |
|||
Select |
|||
When x=0 Then Return 1 |
|||
When datatype(x,'W')=0 Then Return 'nan' |
|||
Otherwise Do |
|||
r=xbase**x |
|||
Numeric Digits xprec |
|||
Return r+0 |
|||
End |
|||
End |
|||
End |
|||
Otherwise |
|||
x=x*self~log(xbase,iprec) |
|||
End |
|||
End |
|||
o=1 |
|||
u=1 |
|||
r=1 |
|||
Do i=1 By 1 Until ra=r |
|||
ra=r |
|||
o=o*x |
|||
u=u*i |
|||
r=r+(o/u) |
|||
End |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::Method log |
|||
/*********************************************************************** |
|||
* log(x,precision) -- returns ln(x) with specified precision |
|||
* log(x,precision,base) -- returns blog(x) with specified precision |
|||
* Three different series are used for ln(x): x in range 0 to 0.5 |
|||
* 0.5 to 1.5 |
|||
* 1.5 to infinity |
|||
***********************************************************************/ |
|||
Expose precision |
|||
Use Strict Arg x,xprec=(precision),xbase='' |
|||
iprec=xprec+100 |
|||
Numeric Digits iprec |
|||
Select |
|||
When x=0 Then Return '-infinity' |
|||
When x<0 Then Return 'nan' |
|||
When x<1 Then r= -self~Log(1/X,xprec) |
|||
Otherwise Do |
|||
do M = 0 until (2 ** M) > X; end |
|||
M = M - 1 |
|||
Z = X / (2 ** M) |
|||
Zeta = (1 - Z) / (1 + Z) |
|||
N = Zeta; Ln = Zeta; Zetasup2 = Zeta * Zeta |
|||
do J = 1 |
|||
N = N * Zetasup2; NewLn = Ln + N / (2 * J + 1) |
|||
if NewLn = Ln then Do |
|||
r= M * self~LN2P(xprec) - 2 * Ln |
|||
Leave |
|||
End |
|||
Ln = NewLn |
|||
end |
|||
End |
|||
End |
|||
If x>0 Then Do |
|||
If xbase>'' Then |
|||
r=r/self~log(xbase,iprec) |
|||
Numeric Digits xprec |
|||
r=r+0 |
|||
End |
|||
Return r |
|||
::Method ln2p |
|||
Parse Arg p |
|||
Numeric Digits p+10 |
|||
If p<=1000 Then |
|||
Return self~ln2() |
|||
n=1/3 |
|||
ln=n |
|||
zetasup2=1/9 |
|||
Do j=1 |
|||
n=n*zetasup2 |
|||
newln=ln+n/(2*j+1) |
|||
If newln=ln Then |
|||
Return 2*ln |
|||
ln=newln |
|||
End |
|||
::Method LN2 |
|||
v='' |
|||
v=v||0.69314718055994530941723212145817656807 |
|||
v=v||5500134360255254120680009493393621969694 |
|||
v=v||7156058633269964186875420014810205706857 |
|||
v=v||3368552023575813055703267075163507596193 |
|||
v=v||0727570828371435190307038623891673471123 |
|||
v=v||3501153644979552391204751726815749320651 |
|||
v=v||5552473413952588295045300709532636664265 |
|||
v=v||4104239157814952043740430385500801944170 |
|||
v=v||6416715186447128399681717845469570262716 |
|||
v=v||3106454615025720740248163777338963855069 |
|||
v=v||5260668341137273873722928956493547025762 |
|||
v=v||6520988596932019650585547647033067936544 |
|||
v=v||3254763274495125040606943814710468994650 |
|||
v=v||6220167720424524529612687946546193165174 |
|||
v=v||6813926725041038025462596568691441928716 |
|||
v=v||0829380317271436778265487756648508567407 |
|||
v=v||7648451464439940461422603193096735402574 |
|||
v=v||4460703080960850474866385231381816767514 |
|||
v=v||3866747664789088143714198549423151997354 |
|||
v=v||8803751658612753529166100071053558249879 |
|||
v=v||4147295092931138971559982056543928717000 |
|||
v=v||7218085761025236889213244971389320378439 |
|||
v=v||3530887748259701715591070882368362758984 |
|||
v=v||2589185353024363421436706118923678919237 |
|||
v=v||231467232172053401649256872747782344535348 |
|||
return V |
|||
::Method log10 |
|||
/*********************************************************************** |
|||
* Return log10(x,prec) specified precision |
|||
***********************************************************************/ |
|||
Expose precision |
|||
Use Strict Arg x,xprec=(precision) |
|||
iprec=xprec+10 |
|||
r=self~log(x,iprec,10) |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::Method pi |
|||
/* REXX ************************************************************* |
|||
* Return pi with the specified precision |
|||
********************************************************************/ |
|||
Expose precision |
|||
Use Strict Arg xprec=(precision) |
|||
p='3.141592653589793238462643383279502884197169399375'||, |
|||
'10582097494459230781640628620899862803482534211706'||, |
|||
'79821480865132823066470938446095505822317253594081'||, |
|||
'28481117450284102701938521105559644622948954930381'||, |
|||
'96442881097566593344612847564823378678316527120190'||, |
|||
'91456485669234603486104543266482133936072602491412'||, |
|||
'73724587006606315588174881520920962829254091715364'||, |
|||
'36789259036001133053054882046652138414695194151160'||, |
|||
'94330572703657595919530921861173819326117931051185'||, |
|||
'48074462379962749567351885752724891227938183011949'||, |
|||
'12983367336244065664308602139494639522473719070217'||, |
|||
'98609437027705392171762931767523846748184676694051'||, |
|||
'32000568127145263560827785771342757789609173637178'||, |
|||
'72146844090122495343014654958537105079227968925892'||, |
|||
'35420199561121290219608640344181598136297747713099'||, |
|||
'60518707211349999998372978049951059731732816096318'||, |
|||
'59502445945534690830264252230825334468503526193118'||, |
|||
'81710100031378387528865875332083814206171776691473'||, |
|||
'03598253490428755468731159562863882353787593751957'||, |
|||
'781857780532171226806613001927876611195909216420199' |
|||
If xprec>1000 Then Do /* more than 1000 digits wanted */ |
|||
iprec=xprec+10 /* internal precision */ |
|||
Numeric Digits iprec |
|||
new=1 |
|||
a=sqrt(2,iprec) |
|||
b=0 |
|||
p=2+a |
|||
Do i=1 By 1 Until p=pi |
|||
pi=p |
|||
y=self~sqrt(a,iprec) |
|||
a1=(y+1/y)/2 |
|||
b1=y*(b+1)/(b+a) |
|||
p=pi*b1*(1+a1)/(1+b1) |
|||
a=a1 |
|||
b=b1 |
|||
End |
|||
End |
|||
Numeric Digits xprec |
|||
Return (p+0) |
|||
::Method power |
|||
/*********************************************************************** |
|||
* power(base,exponent,precision) returns base**exponent |
|||
* -- with specified precision |
|||
***********************************************************************/ |
|||
Expose precision |
|||
Use Strict Arg b,c,xprec=(precision) |
|||
Numeric Digits xprec |
|||
rsign=1 |
|||
If b<0 Then Do /* negative base */ |
|||
If datatype(c,'W') Then Do /* Exponent is an integer */ |
|||
If c//2=1 Then /* .. an odd number */ |
|||
rsign=-1 /* Resuld will be negative */ |
|||
b=abs(b) /* proceed with positive base */ |
|||
End |
|||
Else Do /* Exponent is not an integer */ |
|||
-- Say 'for a negative base ('||b')', |
|||
-- 'exponent ('c') must be an integer' |
|||
Return 'nan' /* Return not a number */ |
|||
End |
|||
End |
|||
If c=0 Then Do |
|||
If b>=0 Then |
|||
r=1 |
|||
End |
|||
Else |
|||
r=self~exp(c,xprec,b) |
|||
If datatype(r)<>'NUM' Then |
|||
Return r |
|||
Return rsign*r |
|||
::Method sqrt |
|||
/* REXX ************************************************************* |
|||
* Return sqrt(x,precision) -- with the specified precision |
|||
********************************************************************/ |
|||
Expose precision type |
|||
Use Strict Arg x,xprec=(precision) |
|||
If x<0 Then Do |
|||
Return 'nan' |
|||
End |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
r0= x |
|||
r = 1 |
|||
Do i=1 By 1 Until r=r0 | (abs(r*r-x)<10**-iprec) |
|||
r0 = r |
|||
r = (r + x/r) / 2 |
|||
End |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::Method sin |
|||
/* REXX ************************************************************* |
|||
* Return sin(x,precision,type) -- with the specified precision |
|||
* xtype = 'R' (radians, default) 'D' (degrees) 'G' (grades) |
|||
* sin(x) = x-(x**3/3!)+(x**5/5!)-(x**7/7!)+-... |
|||
********************************************************************/ |
|||
Expose precision type |
|||
Use Strict Arg x,xprec=(precision),xtype=(type) |
|||
iprec=xprec+10 /* internal precision */ |
|||
Numeric Digits iprec |
|||
/* first use pi constant or compute it if necessary */ |
|||
pi=self~pi(iprec) |
|||
/* normalize x to be between 0 and 2*pi (or equivalent) */ |
|||
/* and convert degrees or grades to radians */ |
|||
xx=x |
|||
Select |
|||
When xtype='R' Then Do |
|||
Do While xx>=pi*2; xx=xx-pi*2; End |
|||
Do While xx<0; xx=xx+pi*2; End |
|||
End |
|||
When xtype='D' Then Do |
|||
Do While xx>=360; xx=xx-360; End |
|||
Do While xx<0; xx=xx+360; End |
|||
xx=xx*pi/180 |
|||
End |
|||
When xtype='G' Then Do |
|||
Do While xx>=400; xx=xx-400; End |
|||
Do While xx<0; xx=xx+400; End |
|||
xx=xx*pi/200 |
|||
End |
|||
End |
|||
/* normalize xx to be between 0 and pi/2 */ |
|||
sign=1 |
|||
Select |
|||
When xx<=pi/2 Then Nop |
|||
When xx<=pi Then xx=pi-xx |
|||
When xx<=3*pi/2 Then Do; sign=-1; xx=xx-pi; End |
|||
Otherwise Do; sign=-1; xx=2*pi-xx; End |
|||
End |
|||
/* now compute the Taylor series for the normalized xx */ |
|||
o=xx |
|||
u=1 |
|||
r=xx |
|||
If abs(xx)<10**(-iprec) Then |
|||
r=0 |
|||
Else Do |
|||
Do i=3 By 2 Until ra=r |
|||
ra=r |
|||
o=-o*xx*xx |
|||
u=u*i*(i-1) |
|||
r=r+(o/u) |
|||
End |
|||
End |
|||
Numeric Digits xprec |
|||
Return sign*(r+0) |
|||
::Method sinh |
|||
/* REXX **************************************************************** |
|||
* Return sinh(x,precision) -- with specified precision |
|||
* sinh(x) = x+(x**3/3!)+(x**5/5!)+(x**7/7!)+-... |
|||
* 920903 Walter Pachl |
|||
***********************************************************************/ |
|||
Expose precision |
|||
Use Strict Arg x,xprec=(precision) |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
o=x |
|||
u=1 |
|||
r=x |
|||
Do i=3 By 2 Until ra=r |
|||
ra=r |
|||
o=o*x*x |
|||
u=u*i*(i-1) |
|||
r=r+(o/u) |
|||
End |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::Method tan |
|||
/* REXX ************************************************************* |
|||
* Return tan(x,precision,type) -- with the specified precision |
|||
* tan(x)=sin(x)/cos(x) |
|||
********************************************************************/ |
|||
Expose precision type |
|||
Use Strict Arg x,xprec=(precision),xtype=(type) |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
s=self~sin(x,iprec,xtype) |
|||
c=self~cos(x,iprec,xtype) |
|||
If c=0 Then |
|||
Return '+infinity' |
|||
t=s/c |
|||
Numeric Digits xprec |
|||
Return (t+0) |
|||
::Method tanh |
|||
/*********************************************************************** |
|||
* Return tanh(x,precision) -- with specified precision |
|||
* tanh(x) = sinh(x)/cosh(x) |
|||
***********************************************************************/ |
|||
Expose precision |
|||
Use Strict Arg x,xprec=(precision) |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
r=self~sinh(x,iprec)/self~cosh(x,iprec) |
|||
Numeric Digits xprec |
|||
Return (r+0) |
|||
::routine rxmarccos public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
If x<-1 | 1<x Then |
|||
Return 'nan' |
|||
return .my.rxm~arccos(x,xprec,xtype) |
|||
::routine rxmarcsin public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
If wordpos(xtype,'R D G')=0 Then Do |
|||
-- Say 'Argument 3 must be R, D, or G' |
|||
Raise Syntax 88.907 array(3,'R, D, or G',xtype) |
|||
End |
|||
If x<-1 | 1<x Then |
|||
Return 'nan' |
|||
return .my.rxm~arcsin(x,xprec,xtype) |
|||
::routine rxmarctan public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
If wordpos(xtype,'R D G')=0 Then Do |
|||
-- Say 'Argument 3 must be R, D, or G' |
|||
Raise Syntax 88.907 array(3,'R, D, or G',xtype) |
|||
End |
|||
return .my.rxm~arctan(x,xprec,xtype) |
|||
::routine rxmarsinh public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
return .my.rxm~arsinh(x,xprec) |
|||
::routine rxmcos public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
If wordpos(xtype,'R D G')=0 Then Do |
|||
-- Say 'Argument 3 must be R, D, or G' |
|||
Raise Syntax 88.907 array(3,'R, D, or G',xtype) |
|||
End |
|||
return .my.rxm~cos(x,xprec,xtype) |
|||
::routine rxmcosh public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
return .my.rxm~cosh(x,xprec) |
|||
::routine rxmcotan public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
If wordpos(xtype,'R D G')=0 Then Do |
|||
-- Say 'Argument 3 must be R, D, or G' |
|||
Raise Syntax 88.907 array(3,'R, D, or G',xtype) |
|||
End |
|||
return .my.rxm~cotan(x,xprec) |
|||
::routine rxmexp public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision),xbase='' |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
If datatype(xbase,'NUM')=0 & xbase<>'' Then Do |
|||
-- Say 'Argument 3 must be omitted or a number' |
|||
Raise Syntax 88.902 array(3,xbase) |
|||
End |
|||
Select |
|||
When x<0 Then Do |
|||
iprec=xprec+10 |
|||
Numeric Digits iprec |
|||
z=.my.rxm~exp(abs(x),iprec,xbase) |
|||
Select |
|||
When z=0 Then Return '+infinity' |
|||
When datatype(z)<>'NUM' Then Return z |
|||
Otherwise r=1/z |
|||
End |
|||
Numeric Digits xprec |
|||
return r+0 |
|||
End |
|||
When x=0 Then Do |
|||
If xbase=0 Then |
|||
Return 'nan' |
|||
Else |
|||
Return 1 |
|||
End |
|||
Otherwise |
|||
return .my.rxm~exp(x,xprec,xbase) |
|||
End |
|||
::routine rxmlog public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision),xbase='' |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
If xbase<>'' &, |
|||
datatype(xbase,'NUM')=0 Then Do |
|||
-- Say 'Argument 3 must be a number' |
|||
Raise Syntax 88.902 array(3,xbase) |
|||
End |
|||
If x=0 Then |
|||
Return '-infinity' |
|||
If x<0 Then |
|||
Return 'nan' |
|||
return .my.rxm~log(x,xprec,xbase) |
|||
::routine rxmlog10 public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
If x=0 Then |
|||
Return '-infinity' |
|||
If x<0 Then |
|||
Return 'nan' |
|||
return .my.rxm~log10(x,xprec) |
|||
::routine rxmpi public |
|||
Use Strict Arg xprec=(.my.rxm~precision) |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
return .my.rxm~pi(xprec) |
|||
::routine rxmpower public |
|||
Use Strict Arg b,e,xprec=(.my.rxm~precision) |
|||
If datatype(b,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,b) |
|||
End |
|||
If datatype(e,'NUM')=0 Then Do |
|||
-- Say 'Argument 2 must be a number' |
|||
Raise Syntax 88.902 array(2,e) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 3 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 3 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(3,1,999999,xprec) |
|||
End |
|||
If b<0 & datatype(e,'W')=0 Then |
|||
Return 'nan' |
|||
return .my.rxm~power(b,e,xprec) |
|||
::routine rxmsqrt public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
Select |
|||
When x<0 Then Return 'nan' |
|||
When x=0 Then Return 0 |
|||
Otherwise |
|||
return .my.rxm~sqrt(x,xprec) |
|||
End |
|||
::routine rxmsin public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
If wordpos(xtype,'R D G')=0 Then Do |
|||
-- Say 'Argument 3 must be R, D, or G' |
|||
Raise Syntax 88.907 array(3,'R, D, or G',xtype) |
|||
End |
|||
return .my.rxm~sin(x,xprec,xtype) |
|||
::routine rxmsinh public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
return .my.rxm~sinh(x,xprec) |
|||
::routine rxmtan public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
If wordpos(xtype,'R D G')=0 Then Do |
|||
-- Say 'Argument 3 must be R, D, or G' |
|||
Raise Syntax 88.907 array(3,'R, D, or G',xtype) |
|||
End |
|||
return .my.rxm~tan(x,xprec,xtype) |
|||
::routine rxmtanh public |
|||
Use Strict Arg x,xprec=(.my.rxm~precision) |
|||
If datatype(x,'NUM')=0 Then Do |
|||
-- Say 'Argument 1 must be a number' |
|||
Raise Syntax 88.902 array(1,x) |
|||
End |
|||
If datatype(xprec,'W')=0 Then Do |
|||
-- Say 'Argument 2 must be a positive whole number' |
|||
Raise Syntax 88.905 array(2,xprec) |
|||
End |
|||
If xprec<1 | 999999<xprec Then Do |
|||
-- Say 'Argument 2 must be a whole number between 1 and 999999' |
|||
Raise Syntax 88.907 array(2,1,999999,xprec) |
|||
End |
|||
return .my.rxm~tanh(x,xprec) |
|||
::routine rxmhelp public |
|||
Use Arg xprec=(.my.rxm~precision),xtype=(.my.rxm~type) |
|||
Say 'precision='xprec |
|||
Say ' type='xtype |
|||
Parse source s; Say ' source='s |
|||
Parse version v; Say ' version='v |
|||
Do si=2 To 5 |
|||
Say substr(sourceline(si),3) |
|||
End |
|||
Say 'You can change the default precision and type as follows:' |
|||
Say " .locaL~my.rxm~precision=50" |
|||
Say " .locaL~my.rxm~type='R'" |
|||
return 0</syntaxhighlight> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
PI = 3.14159265 |
PI = 3.14159265 |
||
Line 1,498: | Line 3,914: | ||
for I#F in [Asin#Sin Acos#Cos Atan#Tan] do |
for I#F in [Asin#Sin Acos#Cos Atan#Tan] do |
||
{System.showInfo {I {F Radians}}#" "#{ToDegrees {I {F Radians}}}} |
{System.showInfo {I {F Radians}}#" "#{ToDegrees {I {F Radians}}}} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Pari accepts only radians; the conversion is simple but not included here. |
Pari accepts only radians; the conversion is simple but not included here. |
||
< |
<syntaxhighlight lang="parigp">cos(Pi/2) |
||
sin(Pi/2) |
sin(Pi/2) |
||
tan(Pi/2) |
tan(Pi/2) |
||
acos(1) |
acos(1) |
||
asin(1) |
asin(1) |
||
atan(1)</ |
atan(1)</syntaxhighlight> |
||
{{works with|PARI/GP|2.4.3 and above}} |
|||
<syntaxhighlight lang="parigp">apply(f->f(1), [cos,sin,tan,acos,asin,atan])</syntaxhighlight> |
|||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
{{libheader|math}} |
{{libheader|math}} |
||
< |
<syntaxhighlight lang="pascal">Program TrigonometricFuntions(output); |
||
uses |
uses |
||
Line 1,531: | Line 3,950: | ||
writeln (arctan(tan(radians)),' Rad., or ', arctan(tan(degree/180*pi))/pi*180,' Deg.'); |
writeln (arctan(tan(radians)),' Rad., or ', arctan(tan(degree/180*pi))/pi*180,' Deg.'); |
||
// ( radians ) / pi * 180 = deg. |
// ( radians ) / pi * 180 = deg. |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
|||
<pre> 7.0710678118654750E-0001 7.0710678118654752E-0001 |
<pre> 7.0710678118654750E-0001 7.0710678118654752E-0001 |
||
7.0710678118654755E-0001 7.0710678118654752E-0001 |
7.0710678118654755E-0001 7.0710678118654752E-0001 |
||
Line 1,543: | Line 3,963: | ||
{{works with|Perl|5.8.8}} |
{{works with|Perl|5.8.8}} |
||
< |
<syntaxhighlight lang="perl">use Math::Trig; |
||
my $angle_degrees = 45; |
my $angle_degrees = 45; |
||
Line 1,559: | Line 3,979: | ||
print $atan, ' ', rad2deg($atan), "\n"; |
print $atan, ' ', rad2deg($atan), "\n"; |
||
my $acot = acot(cot($angle_radians)); |
my $acot = acot(cot($angle_radians)); |
||
print $acot, ' ', rad2deg($acot), "\n";</ |
print $acot, ' ', rad2deg($acot), "\n";</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
0.707106781186547 0.707106781186547 |
0.707106781186547 0.707106781186547 |
||
Line 1,573: | Line 3,993: | ||
</pre> |
</pre> |
||
=={{header| |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
{{works with|Rakudo|#22 "Thousand Oaks"}} |
|||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sin</span><span style="color: #0000FF;">(</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">sin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">90</span><span style="color: #0000FF;">*</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">/</span><span style="color: #000000;">180</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">cos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">*</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">/</span><span style="color: #000000;">180</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">tan</span><span style="color: #0000FF;">(</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">/</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">tan</span><span style="color: #0000FF;">(</span><span style="color: #000000;">45</span><span style="color: #0000FF;">*</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">/</span><span style="color: #000000;">180</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">arcsin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">2</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">arcsin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">180</span><span style="color: #0000FF;">/</span><span style="color: #004600;">PI</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">arccos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">2</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">arccos</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">180</span><span style="color: #0000FF;">/</span><span style="color: #004600;">PI</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">arctan</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">4</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">arctan</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">180</span><span style="color: #0000FF;">/</span><span style="color: #004600;">PI</span> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
|||
<pre> |
|||
1 |
|||
1 |
|||
1 |
|||
1 |
|||
1.0 |
|||
1.0 |
|||
3.141592654 |
|||
90 |
|||
3.141592654 |
|||
90 |
|||
3.141592654 |
|||
45 |
|||
</pre> |
|||
=={{header|PHP}}== |
|||
<lang perl6>say sin(pi/3), ' ', sin 60, 'd'; # 'g' (gradians) and 1 (circles) |
|||
<syntaxhighlight lang="php">$radians = M_PI / 4; |
|||
say cos(pi/4), ' ', cos 45, 'd'; # are also recognized. |
|||
$degrees = 45 * M_PI / 180; |
|||
say tan(pi/6), ' ', tan 30, 'd'; |
|||
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;</syntaxhighlight> |
|||
=={{header|PicoLisp}}== |
|||
say asin(sqrt(3)/2), ' ', asin sqrt(3)/2, 'd'; |
|||
<syntaxhighlight lang="picolisp">(load "@lib/math.l") |
|||
say acos(1/sqrt 2), ' ', acos 1/sqrt(2), 'd'; |
|||
say atan(1/sqrt 3), ' ', atan 1/sqrt(3), 'd';</lang> |
|||
(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) )</syntaxhighlight> |
|||
{{out}} |
|||
<pre>0.707107 0.707107 |
|||
0.707107 0.707107 |
|||
1.000000 1.000000 |
|||
0.785398 44.999986 |
|||
0.785398 44.999986 |
|||
0.785398 44.999986</pre> |
|||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
declare (x, xd, y, v) float; |
declare (x, xd, y, v) float; |
||
Line 1,604: | Line 4,085: | ||
v = cosh(x); put skip list (v); |
v = cosh(x); put skip list (v); |
||
v = tanh(x); y = atanh(v); put skip list (y); |
v = tanh(x); y = atanh(v); put skip list (y); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Results: |
Results: |
||
<pre> |
<pre> |
||
Line 1,623: | Line 4,104: | ||
ATAN2 are accurate to 30 decimal digits. |
ATAN2 are accurate to 30 decimal digits. |
||
< |
<syntaxhighlight lang="plsql">DECLARE |
||
pi NUMBER := 4 * atan(1); |
pi NUMBER := 4 * atan(1); |
||
radians NUMBER := pi / 4; |
radians NUMBER := pi / 4; |
||
Line 1,634: | Line 4,115: | ||
DBMS_OUTPUT.put_line(ACOS(COS(radians)) || ' ' || ACOS(COS(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); |
DBMS_OUTPUT.put_line(ATAN(TAN(radians)) || ' ' || ATAN(TAN(degrees * pi/180)) * 180/pi); |
||
end;</ |
end;</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>,7071067811865475244008443621048490392889 ,7071067811865475244008443621048490392893 |
<pre>,7071067811865475244008443621048490392889 ,7071067811865475244008443621048490392893 |
||
,7071067811865475244008443621048490392783 ,7071067811865475244008443621048490392779 |
,7071067811865475244008443621048490392783 ,7071067811865475244008443621048490392779 |
||
Line 1,645: | Line 4,126: | ||
The following trigonometric functions are also available |
The following trigonometric functions are also available |
||
< |
<syntaxhighlight lang="plsql">ATAN2(n1,n2) --Arctangent(y/x), -pi < result <= +pi |
||
SINH(n) --Hyperbolic sine |
SINH(n) --Hyperbolic sine |
||
COSH(n) --Hyperbolic cosine |
COSH(n) --Hyperbolic cosine |
||
TANH(n) --Hyperbolic tangent</ |
TANH(n) --Hyperbolic tangent</syntaxhighlight> |
||
=={{header|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> |
|||
=={{header|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: |
|||
<pre>0.707107 0.707107 |
|||
0.707107 0.707107 |
|||
1.000000 1.000000 |
|||
0.785398 44.999986 |
|||
0.785398 44.999986 |
|||
0.785398 44.999986</pre> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
Line 1,693: | Line 4,135: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="pop11">sin(30) => |
||
cos(45) => |
cos(45) => |
||
tan(45) => |
tan(45) => |
||
Line 1,707: | Line 4,149: | ||
arcsin(0.7) => |
arcsin(0.7) => |
||
arccos(0.7) => |
arccos(0.7) => |
||
arctan(0.7) =></ |
arctan(0.7) =></syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
< |
<syntaxhighlight lang="postscript"> |
||
90 sin = |
90 sin = |
||
Line 1,722: | Line 4,164: | ||
3 sqrt 1 atan = |
3 sqrt 1 atan = |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
|||
Output |
|||
<pre> |
<pre> |
||
1.0 |
1.0 |
||
Line 1,736: | Line 4,178: | ||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
{{Trans|C}} |
{{Trans|C}} |
||
< |
<syntaxhighlight lang="powershell">$rad = [Math]::PI / 4 |
||
$deg = 45 |
$deg = 45 |
||
'{0,10} {1,10}' -f 'Radians','Degrees' |
'{0,10} {1,10}' -f 'Radians','Degrees' |
||
Line 1,747: | Line 4,189: | ||
'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) |
'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) |
||
$temp = [Math]::Atan([Math]::Tan($rad)) |
$temp = [Math]::Atan([Math]::Tan($rad)) |
||
'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI)</ |
'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI)</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> Radians Degrees |
<pre> Radians Degrees |
||
0,707107 0,707107 |
0,707107 0,707107 |
||
Line 1,756: | Line 4,198: | ||
0,785398 45,000000 |
0,785398 45,000000 |
||
0,785398 45,000000</pre> |
0,785398 45,000000</pre> |
||
===A More "PowerShelly" Way=== |
|||
I would send the output as an array of objects containing the (<code>[double]</code>) properties: '''Radians''' and '''Degrees'''. |
|||
Notice the difference between the last decimal place in the first two objects. If you were calculating coordinates as a civil engineer or land surveyor this difference could affect your measurments. Additionally, the output is an array of objects containing <code>[double]</code> values rather than an array of strings. |
|||
<syntaxhighlight lang="powershell"> |
|||
$radians = [Math]::PI / 4 |
|||
$degrees = 45 |
|||
[PSCustomObject]@{Radians=[Math]::Sin($radians); Degrees=[Math]::Sin($degrees * [Math]::PI / 180)} |
|||
[PSCustomObject]@{Radians=[Math]::Cos($radians); Degrees=[Math]::Cos($degrees * [Math]::PI / 180)} |
|||
[PSCustomObject]@{Radians=[Math]::Tan($radians); Degrees=[Math]::Tan($degrees * [Math]::PI / 180)} |
|||
[double]$tempVar = [Math]::Asin([Math]::Sin($radians)) |
|||
[PSCustomObject]@{Radians=$tempVar; Degrees=$tempVar * 180 / [Math]::PI} |
|||
[double]$tempVar = [Math]::Acos([Math]::Cos($radians)) |
|||
[PSCustomObject]@{Radians=$tempVar; Degrees=$tempVar * 180 / [Math]::PI} |
|||
[double]$tempVar = [Math]::Atan([Math]::Tan($radians)) |
|||
[PSCustomObject]@{Radians=$tempVar; Degrees=$tempVar * 180 / [Math]::PI} |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
Radians Degrees |
|||
------- ------- |
|||
0.707106781186547 0.707106781186547 |
|||
0.707106781186548 0.707106781186548 |
|||
1 1 |
|||
0.785398163397448 45 |
|||
0.785398163397448 45 |
|||
0.785398163397448 45 |
|||
</pre> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">OpenConsole() |
||
Macro DegToRad(deg) |
Macro DegToRad(deg) |
||
Line 1,782: | Line 4,256: | ||
PrintN(StrF(arctan)+" "+Str(RadToDeg(arctan))) |
PrintN(StrF(arctan)+" "+Str(RadToDeg(arctan))) |
||
Input()</ |
Input()</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>0.707107 0.707107 |
<pre>0.707107 0.707107 |
||
0.707107 0.707107 |
0.707107 0.707107 |
||
Line 1,794: | Line 4,268: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
Python's <tt>math</tt> module contains all six functions. |
Python's <tt>math</tt> module contains all six functions. <br> |
||
The functions all accept radians only, so conversion is necessary |
|||
when dealing with degrees. <br> |
|||
The <tt>math</tt> module also has <tt>degrees()</tt> and <tt>radians()</tt> functions for easy conversion. |
|||
< |
<syntaxhighlight 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. |
Type "copyright", "credits" or "license()" for more information. |
||
>>> from math import degrees, radians, sin, cos, tan, asin, acos, atan, pi |
>>> from math import degrees, radians, sin, cos, tan, asin, acos, atan, pi |
||
Line 1,815: | Line 4,292: | ||
>>> print("Arctangent:", arctangent, degrees(arctangent)) |
>>> print("Arctangent:", arctangent, degrees(arctangent)) |
||
Arctangent: 0.7853981633974483 45.0 |
Arctangent: 0.7853981633974483 45.0 |
||
>>> </ |
>>> </syntaxhighlight> |
||
=={{header|Quackery}}== |
|||
<code>v**</code> is defined at [[Exponentiation operator#Quackery]]. |
|||
'''Please note''', the code presented here is sufficient to the task, but is not a practical implementation for the reasons discussed below. The intent of this entry is to invite discussion on the subject of Padé Approximants, the method used here. To that end I have opened a section on the subject in the Discussion page of this task, and invite you to contribute to it if you have useful knowledge of Padé Approximants. |
|||
Full disclosure - I am not a mathematician, I am an amateur programmer who has recently heard of Padé Approximants and is desirous of learning more, as they look to be a useful tool, but not a panacea. |
|||
A search of Rosetta Code at the time of writing (14 July 2021) finds no references to Padé or Pade on the site. A more general search of the Internet turns up such phrases as "is the "best" approximation of a function by a rational function of given order" and "The unreasonable effectiveness of Pade approximation", which piqued my interest. Generally there are scholarly papers in the subject that whoosh right over my head, and very little at the "pop-maths" level, i.e. no videos by my go-to YouTube channels - numberphile/computerphile, 3blue1brown, mathologer. |
|||
In the absence of sources pitched at my level, this is the methodology I have developed to create this code. |
|||
''Step 1''. Use Wolfram Alpha to find Padé Approximants for a function. Here is the relevant documentation for Mathematica, which also applies to Wolfram Alpha. Link: [https://reference.wolfram.com/language/ref/PadeApproximant.html PadeApproximant]. |
|||
Here are the inputs to Wolfram Alpha used in generating this Quackery code. [https://www.wolframalpha.com/input/?i=PadeApproximant%5BSin%5Bx%5D%2C+%7Bx%2C+0%2C+%7B6%2C6%7D%7D%5D sin], [https://www.wolframalpha.com/input/?i=PadeApproximant%5Bcos%5Bx%5D%2C+%7Bx%2C+0%2C+%7B7%2C7%7D%7D%5D cos], [https://www.wolframalpha.com/input/?i=PadeApproximant%5Barccos%5Bx%5D%2C+%7Bx%2C+0%2C+%7B6%2C6%7D%7D%5D tan], [https://www.wolframalpha.com/input/?i=PadeApproximant%5Barcsin%5Bx%5D%2C+%7Bx%2C+0%2C+%7B6%2C6%7D%7D%5D arcsin], [https://www.wolframalpha.com/input/?i=PadeApproximant%5Barccos%5Bx%5D%2C+%7Bx%2C+0%2C+%7B6%2C6%7D%7D%5D+%29 arccos], and [https://www.wolframalpha.com/input/?i=PadeApproximant%5Barctan%5Bx%5D%2C+%7Bx%2C+0%2C+%7B7%2C7%7D%7D%5D arctan]. |
|||
Note that the exact result for <code>arccos</code> includes several instances of the irrational number π, which is not ideal given that the intent is to generate a rational approximation, so instead I used the identity arccos(x)=π/2-arcsin(x), which Wolfram Alpha lists amongst the "Alternate forms", reducing the number of uses of π to one. |
|||
''Step 2''. Use GeoGebra to see the range of arguments over which the Padé approximant is valid, and to identify the range in which it will return values correct to a given number of decimal places. In each of the following examples, function <code>f</code> is a Padé Approximant, function <code>g</code> is the function that <code>f</code> is approximating, and function <code>h</code> is the difference between <code>f</code> and <code>g</code>, multiplied by <code>10^n</code>, where <code>n</code> can be varied with a slider. Where the <code>h</code> line is very close to zero, the approximation will be good to <code>n</code> decimal places. |
|||
Your attention is drawn to the task output for <code>arccos</code>, which is only good to a couple of decimal places for the argument passed to it. This is explained by the corresponding graph in Geogebra, where we can see that the argument is outside the safe (i.e. <code>h</code> is close to zero) range for anything other than very small values of <code>n</code>. |
|||
Geogebra graphs for the functions defined in this task: [https://www.geogebra.org/m/nygvcs2s sin], [https://www.geogebra.org/m/q3myjbfd cos], [https://www.geogebra.org/m/fsdfzzfs tan], [https://www.geogebra.org/m/n6jctj7c arcsin], [https://www.geogebra.org/m/kkrhjksu arccos], [https://www.geogebra.org/m/ge4qpppf arctan]. |
|||
''Step 3''. Iterate over steps 1 and 2 until you find appropriate Padé Approximants for the task at hand, or conclude that none exist. Assuming the former; |
|||
''Step 4''. Code in a suitable language (i.e. probably not Quackery - efficiency was not a design criterion for Quackery, the language is intended to be the simplest possible introduction to Concatenative/Stack based programming, and is consequently suitable for hobbyist and educational use only) with any obvious optimisations, and use symmetries and identities of the function to extend the range of arguments that can be passed to it. (Not done here - the code serves solely to demonstrate the one-to-one correspondence between a proof-of-concept coding and the formula returned by Wolfram Alpha.) |
|||
Note also that the approximation of π/2 is good to 40 decimal places. This is intentional overkill, so that I can be sure that it is not the cause of any inaccuracies. Reducing the size of the numerator and denomination to more sensible values would be part of the optimisation process. |
|||
<syntaxhighlight lang="quackery"> [ $" bigrat.qky' loadfile ] now! |
|||
[ 2646693125139304345 |
|||
1684937174853026414 ] is pi/2 ( --> n/d ) |
|||
[ 2dup |
|||
2dup 3 v** 2363 18183 v* v- |
|||
2over 5 v** 12671 4363920 v* v+ |
|||
2swap 1 1 |
|||
2over 2 v** 445 12122 v* v+ |
|||
2over 4 v** 601 872784 v* v+ |
|||
2swap 6 v** 121 16662240 v* v+ |
|||
v/ ] is sin ( n/d --> n/d ) |
|||
[ 1 1 |
|||
2over 2 v** 3665 7788 v* v- |
|||
2over 4 v** 711 25960 v* v+ |
|||
2over 6 v** 2923 7850304 v* v- |
|||
2swap 1 1 |
|||
2over 2 v** 229 7788 v* v+ |
|||
2over 4 v** 1 2360 v* v+ |
|||
2swap 6 v** 127 39251520 v* v+ |
|||
v/ ] is cos ( n/d --> n/d ) |
|||
[ 2dup |
|||
2dup 3 v** 5 39 v* v- |
|||
2over 5 v** 2 715 v* v+ |
|||
2over 7 v** 1 135135 v* v- |
|||
2swap 1 1 |
|||
2over 2 v** 6 13 v* v- |
|||
2over 4 v** 10 429 v* v+ |
|||
2swap 6 v** 4 19305 v* v- |
|||
v/ ] is tan ( n/d --> n/d ) |
|||
[ 2dup |
|||
2dup 3 v** 2318543 2278617 v* v- |
|||
2over 5 v** 12022609 60763120 v* v+ |
|||
2swap 1 1 |
|||
2over 2 v** 1798875 1519078 v* v- |
|||
2over 4 v** 3891575 12152624 v* v+ |
|||
2swap 6 v** 4695545 510410208 v* v- |
|||
v/ ] is arcsin ( n/d --> n/d ) |
|||
[ pi/2 2swap arcsin v- ] is arccos ( n/d --> n/d ) |
|||
[ 2dup |
|||
2dup 3 v** 50 39 v* v+ |
|||
2over 5 v** 283 715 v* v+ |
|||
2over 7 v** 256 15015 v* v+ |
|||
2swap 1 1 |
|||
2over 2 v** 21 13 v* v+ |
|||
2over 4 v** 105 143 v* v+ |
|||
2swap 6 v** 35 429 v* v+ |
|||
v/ ] is arctan ( n/d --> n/d ) |
|||
[ pi/2 v* 90 1 v/ ] is deg->rad ( n/d --> n/d ) |
|||
[ pi/2 v/ 90 1 v* ] is rad->deg ( n/d --> n/d ) |
|||
say "With an argument of 0.5 radians" |
|||
cr cr |
|||
$ "0.5" $->v drop |
|||
sin |
|||
say "Sin approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 0.47942553860420300027..." |
|||
cr cr |
|||
$ "0.5" $->v drop |
|||
cos |
|||
say "Cos approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 0.87758256189037271611..." |
|||
cr cr |
|||
$ "0.5" $->v drop |
|||
tan |
|||
say "Tan approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 0.54630248984379051325..." |
|||
cr cr cr |
|||
say "To radians, using approximated values from previous computations" |
|||
cr cr |
|||
$ "0.47942553860423933121" $->v drop |
|||
arcsin |
|||
say "Arcsin approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 0.5" |
|||
cr cr |
|||
$ "0.87758256189037190908" $->v drop |
|||
arccos |
|||
say "Arccos approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 0.5" |
|||
cr cr |
|||
$ "0.54630248984379037103" $->v drop |
|||
arctan |
|||
say "Arctan approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 0.5" |
|||
cr cr cr |
|||
say "0.5 radians is approx 28.64788976 degrees" cr |
|||
cr |
|||
$ "28.64788976" $->v drop |
|||
deg->rad sin |
|||
say "Sin approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 0.47942553865718102604..." |
|||
cr cr |
|||
$ "28.64788976" $->v drop |
|||
deg->rad cos |
|||
say "Cos approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 0.87758256186143068872..." |
|||
cr cr |
|||
$ "28.64788976" $->v drop |
|||
deg->rad tan |
|||
say "Tan approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 0.54630248992217530618..." |
|||
cr cr cr |
|||
say "To degrees, using approximated values from previous computations" |
|||
cr cr |
|||
$ "0.47942553865721735699" $->v drop |
|||
arcsin rad->deg |
|||
say "Arcsin approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 28.64788976..." |
|||
cr cr |
|||
$ "0.87758256186142988169" $->v drop |
|||
arccos rad->deg |
|||
say "Arccos approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 28.64788976..." |
|||
cr cr |
|||
$ "0.54630248992217516396" $->v drop |
|||
arctan rad->deg |
|||
say "Arctan approximation: " 20 point$ echo$ cr |
|||
say " Actual value: 28.64788976..."</syntaxhighlight> |
|||
{{out}} |
|||
<pre>With an argument of 0.5 radians |
|||
Sin approximation: 0.47942553860423933121 |
|||
Actual value: 0.47942553860420300027... |
|||
Cos approximation: 0.87758256189037190908 |
|||
Actual value: 0.87758256189037271611... |
|||
Tan approximation: 0.54630248984379037103 |
|||
Actual value: 0.54630248984379051325... |
|||
To radians, using approximated values from previous computations |
|||
Arcsin approximation: 0.49999997409078633068 |
|||
Actual value: 0.5 |
|||
Arccos approximation: 0.50090902435100642663 |
|||
Actual value: 0.5 |
|||
Arctan approximation: 0.50000000390223900073 |
|||
Actual value: 0.5 |
|||
0.5 radians is approx 28.64788976 degrees |
|||
Sin approximation: 0.47942553865721735699 |
|||
Actual value: 0.47942553865718102604... |
|||
Cos approximation: 0.87758256186142988169 |
|||
Actual value: 0.87758256186143068872... |
|||
Tan approximation: 0.54630248992217516396 |
|||
Actual value: 0.54630248992217530618... |
|||
To degrees, using approximated values from previous computations |
|||
Arcsin approximation: 28.64788827551140385372 |
|||
Actual value: 28.64788976... |
|||
Arccos approximation: 28.69997301874556855873 |
|||
Actual value: 28.64788976... |
|||
Arctan approximation: 28.64788998358182581534 |
|||
Actual value: 28.64788976... |
|||
Stack empty. |
|||
</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r">deg <- function(radians) 180*radians/pi |
||
rad <- function(degrees) degrees*pi/180 |
rad <- function(degrees) degrees*pi/180 |
||
sind <- function(ang) sin(rad(ang)) |
sind <- function(ang) sin(rad(ang)) |
||
Line 1,840: | Line 4,525: | ||
print( c( asin(S), asind(S) ) ) |
print( c( asin(S), asind(S) ) ) |
||
print( c( acos(C), acosd(C) ) ) |
print( c( acos(C), acosd(C) ) ) |
||
print( c( atan(T), atand(T) ) )</ |
print( c( atan(T), atand(T) ) )</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define radians (/ pi 4)) |
(define radians (/ pi 4)) |
||
(define degrees 45) |
(define degrees 45) |
||
Line 1,860: | Line 4,545: | ||
(define arctan (atan (tan radians))) |
(define arctan (atan (tan radians))) |
||
(display (format "~a ~a" arctan (* arctan (/ 180 pi))))</ |
(display (format "~a ~a" arctan (* arctan (/ 180 pi))))</syntaxhighlight> |
||
=={{header|Raku}}== |
|||
(formerly Perl 6) Borrow the degree to radian routine from [https://rosettacode.org/wiki/Length_of_an_arc_between_two_angles#Raku here]. |
|||
{{works with|Rakudo|2020.12}} |
|||
<syntaxhighlight lang="raku" line># 20210212 Updated Raku programming solution |
|||
sub postfix:<°> (\ᵒ) { ᵒ × τ / 360 } |
|||
sub postfix:<㎭🡆°> (\ᶜ) { ᶜ / π × 180 } |
|||
say sin π/3 ; |
|||
say sin 60° ; |
|||
say cos π/4 ; |
|||
say cos 45° ; |
|||
say tan π/6 ; |
|||
say tan 30° ; |
|||
( asin(3.sqrt/2), acos(1/sqrt 2), atan(1/sqrt 3) )».&{ .say and .㎭🡆°.say }</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0.8660254037844386 |
|||
0.8660254037844386 |
|||
0.7071067811865476 |
|||
0.7071067811865476 |
|||
0.5773502691896257 |
|||
0.5773502691896257 |
|||
1.0471975511965976 |
|||
60 |
|||
0.7853981633974484 |
|||
45.00000000000001 |
|||
0.5235987755982989 |
|||
30.000000000000004 |
|||
</pre> |
|||
=={{header|RapidQ}}== |
=={{header|RapidQ}}== |
||
< |
<syntaxhighlight lang="rapidq">$APPTYPE CONSOLE |
||
$TYPECHECK ON |
$TYPECHECK ON |
||
Line 1,895: | Line 4,615: | ||
pause("Press any key to continue.") |
pause("Press any key to continue.") |
||
END 'MAIN</ |
END 'MAIN</syntaxhighlight> |
||
=={{header|Rapira}}== |
|||
<syntaxhighlight lang="rapira">output: sin(pi/2), " ", cos(0), " ", tg(pi/4)</syntaxhighlight> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">REBOL [ |
||
Title: "Trigonometric Functions" |
Title: "Trigonometric Functions" |
||
Author: oofoe |
|||
Date: 2009-12-07 |
|||
URL: http://rosettacode.org/wiki/Trigonometric_Functions |
URL: http://rosettacode.org/wiki/Trigonometric_Functions |
||
] |
] |
||
Line 1,926: | Line 4,647: | ||
arctan: arctangent tangent degrees |
arctan: arctangent tangent degrees |
||
print [d2r arctan arctan]</ |
print [d2r arctan arctan]</syntaxhighlight> |
||
Output: |
|||
{{out}} |
|||
<pre>0.707106781186547 0.707106781186547 |
<pre>0.707106781186547 0.707106781186547 |
||
0.707106781186548 0.707106781186548 |
0.707106781186548 0.707106781186548 |
||
Line 1,938: | Line 4,658: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
The REXX language doesn't have any trig functions (or for that matter, a square root [SQRT] function), so if higher math |
The REXX language doesn't have any trig functions (or for that matter, a square root [SQRT] function), so if higher math |
||
<br>functions are wanted, you have to roll your own. Some of the normal/regular trigonometric functions are included here. |
<br>functions are wanted, you'll have to roll your own. Some of the normal/regular trigonometric functions are included here. |
||
┌──────────────────────────────────────────────────────────────────────────┐ |
|||
│ One common method that ensures enough accuracy in REXX is specifying │ |
|||
│ more precision (via NUMERIC DIGITS nnn) than is needed, and then │ |
|||
│ displaying the number of digits that are 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. │ |
|||
└──────────────────────────────────────────────────────────────────────────┘ |
|||
Most math (POW, EXP, LOG, LN, GAMMA, etc.), |
Most math (POW, EXP, LOG, LN, GAMMA, etc.), trigonometric, and hyperbolic functions need only five extra digits, but ten |
||
<br>extra digits is safer in case the argument is close to an asymptotic point or a multiple or fractional part of pi or somesuch. |
<br>extra digits is safer in case the argument is close to an asymptotic point or a multiple or fractional part of pi or somesuch. |
||
<br>It should also be noted that both the '''pi''' and '''e''' constants have only around 77 decimal digits as included here, if more |
|||
<br>precision is needed, those constants should be extended. Both '''pi''' and '''e''' could've been shown with more precision, |
|||
<br>but having large precision numbers would add to this REXX program's length. If anybody wishes to see this REXX version of |
|||
<br>extended digits for '''pi''' or '''e''', I could extend them to any almost any precision (as a REXX constant). Normally, a REXX |
|||
<br>(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 |
|||
It should also be noted that both the '''pi''' and '''e''' constants have only around 77 decimal digits as included here, if more |
|||
do j=-180 to +180 by 15 /*let's just do a half-Monty. */ |
|||
<br>precision is needed, those constants should be extended. Both '''pi''' and '''e''' could've been shown with more precision, |
|||
stuff = right(j,4) 'degrees, rads='show( d2r(j)), |
|||
<br>but having large precision numbers would add to this REXX program's length. If anybody wishes to see this REXX version |
|||
' sin='show(sinD(j)), |
|||
<br>of extended digits for '''pi''' or '''e''', they could be extended to any almost any precision (as a REXX constant). Normally, |
|||
' cos='show(cosD(J)) |
|||
<br>a REXX (external) subroutine is used for such purposes so as to not make the program using the constant unwieldy large. |
|||
/*don't let TAN go postal.*/ |
|||
<syntaxhighlight lang="rexx">/*REXX program demonstrates some common trig functions (30 decimal digits are shown).*/ |
|||
if abs(j)\==90 then stuff=stuff ' tan='show(tanD(j)) |
|||
showdigs= 25 /*show only 25 digits of number. */ |
|||
say stuff |
|||
numeric digits showdigs + 10 /*DIGITS default is 9, but use */ |
|||
end /*j*/ |
|||
/*extra digs to prevent rounding.*/ |
|||
say 'Using' showdigs 'decimal digits precision.' /*show # decimal digs being used.*/ |
|||
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 TANGENT 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.*/ |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a |
|||
if a>1 then call AsinErr x /*X argument is out of range. */ |
|||
if a >= sqrt(2) * .5 then return sign(x) * acos( sqrt(1 - aa), '-ASIN') |
|||
do j=2 by 2 until p=z; p=z; o= o * aa * (j-1) / j; z= z +o / (j+1); end |
|||
return z /* [↑] compute until no noise. */ |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
Acos: procedure; parse arg x; if x<-1 | x>1 then call AcosErr; return pi()*.5 - Asin(x) |
|||
AcosD: return r2d( Acos( arg(1) ) ) |
|||
AsinD: return r2d( Asin( arg(1) ) ) |
|||
cosD: return cos( d2r( arg(1) ) ) |
|||
sinD: return sin( d2r( d2d( arg(1) ) ) ) |
|||
tan: procedure; parse 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 ──► a unit circle*/ |
|||
d2r: return r2r( d2d( arg(1) )*pi() / 180) /*convert degrees ──► radians. */ |
|||
r2d: return d2d( ( arg(1) * 180 / pi() ) ) /*convert radians ──► degrees. */ |
|||
r2r: return arg(1) // (pi() *2) /*normalize radians ──► a 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 |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
Atan: procedure; parse arg x; if abs(x)=1 then return pi() * .25 * sign(x) |
|||
return Asin(x / sqrt(1 + x*x) ) |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
cos: procedure; parse arg x; x= r2r(x); if x=0 then return 1; a= abs(x) |
|||
numeric fuzz min(6, digits() - 3); if a=pi then return -1; pih= pi * .5 |
|||
if a=pih | a=pih*3 then return 0; pit= pi/3; if a=pit then return .5 |
|||
if a=pit + pit then return -.5; return .sinCos(1, -1) |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
sin: procedure; arg x;x=r2r(x);if x=0 then return 0;numeric fuzz min(5,max(1,digits()-3)) |
|||
if x=pi*.5 then return 1; if x==pi * 1.5 then return -1 |
|||
if abs(x)=pi then return 0; return .sinCos(x,1) |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
.sinCos: parse arg z 1 _,i; q= x*x |
|||
do k=2 by 2 until p=z; p= z; _= - _ * q / (k * (k+i) ); z= z + _; end |
|||
return z |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9; h= d+6 |
|||
numeric digits; numeric form; if x<0 then do; x= -x; i= 'i'; end |
|||
parse value format(x, 2, 1, , 0) 'E0' with g 'E' _ .; g= g *.5'e'_ % 2 |
|||
do j=0 while h>9; m.j=h; h= h % 2 + 1; end /*j*/ |
|||
do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g) * .5; end /*k*/ |
|||
numeric digits d; return (g/1)i /*make complex if X < 0.*/ |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
e: e = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 |
|||
return e /*Note: the actual E subroutine returns E's accuracy that */ |
|||
/*matches the current NUMERIC DIGITS, up to 1 million digits.*/ |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
exp: procedure; parse 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= e()**ix * z; return z |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 |
|||
return pi /*Note: the actual 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. */</syntaxhighlight> |
|||
Programming note: |
|||
╔═════════════════════════════════════════════════════════════════════════════╗ |
|||
║ Functions that are not included here are (among others): ║ |
|||
║ ║ |
|||
║ some of the usual higher-math functions normally associated with trig ║ |
|||
║ functions: POW, GAMMA, LGGAMMA, ERF, ERFC, ROOT, ATAN2, ║ |
|||
║ LOG (LN), LOG2, LOG10, and all of the ║ |
|||
║ hyperbolic trigonometric functions and their inverses (too many to list ║ |
|||
║ here), ║ |
|||
║ angle conversions/normalizations: degrees/radians/grads/mils: ║ |
|||
║ a circle ≡ 2 pi radians ≡ 360 degrees ≡ 400 grads ≡ 6400 mils. ║ |
|||
║ ║ |
|||
║ Some of the other trigonometric functions are (hyphens added intentionally):║ |
|||
║ ║ |
|||
║ 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 ver-cosine) ║ |
|||
║ VSN (versed sine or ver-sine) ║ |
|||
║ XCS (ex-secant) ║ |
|||
║ COS/SIN/TAN cardinal (damped COS/SIN/TAN functions) ║ |
|||
║ COS/SIN integral ║ |
|||
║ ║ |
|||
║ and all pertinent inverses of the above functions (AVSN, ACVS, ···). ║ |
|||
╚═════════════════════════════════════════════════════════════════════════════╝ |
|||
{{out|output}} |
|||
(Shown at three-quarter size.) |
|||
say; do k=-1 to +1 by 1/2 /*keep the Arc-functions happy. */ |
|||
<pre style="font-size:75%> |
|||
say right(k,4) 'radians, degs='show( r2d(k)), |
|||
Using 25 decimal digits precision. |
|||
' 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 |
|||
-180 degrees, rads= -3.1415926535897932384626 sin= 0 cos= -1 tan= 0 |
|||
Atan: procedure; arg x; if abs(x)=1 then return pi()/4*sign(x) |
|||
-165 degrees, rads= -2.8797932657906438019240 sin= -0.2588190451025207623488 cos= -0.9659258262890682867497 tan= 0.2679491924311227064725 |
|||
return Asin(x/sqrt(1+x**2)) |
|||
-150 degrees, rads= -2.6179938779914943653855 sin= -0.5 cos= -0.8660254037844386467637 tan= 0.5773502691896257645091 |
|||
-135 degrees, rads= -2.3561944901923449288469 sin= -0.7071067811865475244008 cos= -0.7071067811865475244008 tan= 1 |
|||
-120 degrees, rads= -2.0943951023931954923084 sin= -0.8660254037844386467637 cos= -0.5 tan= 1.7320508075688772935274 |
|||
-105 degrees, rads= -1.8325957145940460557698 sin= -0.9659258262890682867497 cos= -0.2588190451025207623488 tan= 3.7320508075688772935274 |
|||
-90 degrees, rads= -1.5707963267948966192313 sin= -1 cos= 0 |
|||
-75 degrees, rads= -1.3089969389957471826927 sin= -0.9659258262890682867497 cos= 0.2588190451025207623488 tan= -3.7320508075688772935274 |
|||
-60 degrees, rads= -1.0471975511965977461542 sin= -0.8660254037844386467637 cos= 0.5 tan= -1.7320508075688772935274 |
|||
-45 degrees, rads= -0.7853981633974483096156 sin= -0.7071067811865475244008 cos= 0.7071067811865475244008 tan= -1 |
|||
-30 degrees, rads= -0.5235987755982988730771 sin= -0.5 cos= 0.8660254037844386467637 tan= -0.5773502691896257645091 |
|||
-15 degrees, rads= -0.2617993877991494365385 sin= -0.2588190451025207623488 cos= 0.9659258262890682867497 tan= -0.2679491924311227064725 |
|||
0 degrees, rads= 0 sin= 0 cos= 1 tan= 0 |
|||
15 degrees, rads= 0.2617993877991494365385 sin= 0.2588190451025207623488 cos= 0.9659258262890682867497 tan= 0.2679491924311227064725 |
|||
30 degrees, rads= 0.5235987755982988730771 sin= 0.5 cos= 0.8660254037844386467637 tan= 0.5773502691896257645091 |
|||
45 degrees, rads= 0.7853981633974483096156 sin= 0.7071067811865475244008 cos= 0.7071067811865475244008 tan= 1 |
|||
60 degrees, rads= 1.0471975511965977461542 sin= 0.8660254037844386467637 cos= 0.5 tan= 1.7320508075688772935274 |
|||
75 degrees, rads= 1.3089969389957471826927 sin= 0.9659258262890682867497 cos= 0.2588190451025207623488 tan= 3.7320508075688772935274 |
|||
90 degrees, rads= 1.5707963267948966192313 sin= 1 cos= 0 |
|||
105 degrees, rads= 1.8325957145940460557698 sin= 0.9659258262890682867497 cos= -0.2588190451025207623488 tan= -3.7320508075688772935274 |
|||
120 degrees, rads= 2.0943951023931954923084 sin= 0.8660254037844386467637 cos= -0.5 tan= -1.7320508075688772935274 |
|||
135 degrees, rads= 2.3561944901923449288469 sin= 0.7071067811865475244008 cos= -0.7071067811865475244008 tan= -1 |
|||
150 degrees, rads= 2.6179938779914943653855 sin= 0.5 cos= -0.8660254037844386467637 tan= -0.5773502691896257645091 |
|||
165 degrees, rads= 2.8797932657906438019240 sin= 0.2588190451025207623488 cos= -0.9659258262890682867497 tan= -0.2679491924311227064725 |
|||
180 degrees, rads= 3.1415926535897932384626 sin= 0 cos= -1 tan= 0 |
|||
-1 radians, degs= -57.295779513082320876798 Acos= 3.1415926535897932384626 Asin= -1.5707963267948966192313 Atan= -0.7853981633974483096156 |
|||
cos: procedure; arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9) |
|||
-0.5 radians, degs= -28.647889756541160438399 Acos= 2.0943951023931954923084 Asin= -0.5235987755982988730771 Atan= -0.4636476090008061162142 |
|||
if a=pi() then return -1; if a=pi()/2 | a=2*pi() then return 0 |
|||
0 radians, degs= 0 Acos= 1.5707963267948966192313 Asin= 0 Atan= 0 |
|||
if a=pi()/3 then return .5; if a=2*pi()/3 then return -.5 |
|||
0.5 radians, degs= 28.647889756541160438399 Acos= 1.0471975511965977461542 Asin= 0.5235987755982988730771 Atan= 0.4636476090008061162142 |
|||
return .sinCos(1,1,-1) |
|||
1.0 radians, degs= 57.295779513082320876798 Acos= 0 Asin= 1.5707963267948966192313 Atan= 0.7853981633974483096156 |
|||
</pre> |
|||
=={{header|Ring}}== |
|||
sin: procedure; arg x; x=r2r(x); numeric fuzz min(5,digits()-3) |
|||
<syntaxhighlight lang="ring"> |
|||
if abs(x)=pi() then return 0; return .sinCos(x,x,1) |
|||
pi = 3.14 |
|||
decimals(8) |
|||
see "sin(pi/4.0) = " + sin(pi/4.0) + nl |
|||
see "cos(pi/4.0) = " + cos(pi/4.0) + nl |
|||
see "tan(pi/4.0) = " + tan(pi/4.0)+ nl |
|||
see "asin(sin(pi/4.0)) = " + asin(sin(pi/4.0)) + nl |
|||
see "acos(cos(pi/4.0)) = " + acos(cos(pi/4.0)) + nl |
|||
see "atan(tan(pi/4.0)) = " + atan(tan(pi/4.0)) + nl |
|||
see "atan2(3,4) = " + atan2(3,4) + nl |
|||
</syntaxhighlight> |
|||
=={{header|RPL}}== |
|||
.sinCos: parse arg z 1 p,_,i; x=x*x |
|||
RPL has somewhere a system flag that defines if arguments passed to trigonometric functions are in degrees or radians. The words <code>DEG</code> and <code>RAD</code> set the flag appropriately. |
|||
do k=2 by 2; _=-_*x/(k*(k+i));z=z+_;if z=p then leave;p=z;end; return z |
|||
We can therefore answer the task so: |
|||
π 4 / →NUM 'XRAD' STO |
|||
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits();numeric digits 11 |
|||
45 'XDEG' STO |
|||
g=.sqrtGuess(); do j=0 while p>9; m.j=p; p=p%2+1; end |
|||
XRAD RAD SIN XDEG DEG SIN |
|||
do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end |
|||
which will return <code>.707106781187</code> 2 times. |
|||
numeric digits d; return g/1 |
|||
Another way is to stay in the same trigonometric mode and use <code>D→R</code> or <code>R→D</code> conversion words. This is the way used below: |
|||
.sqrtGuess: if x<0 then call sqrtErr; numeric form; m.=11; p=d+d%4+2 |
|||
RAD |
|||
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 |
|||
π 4 / →NUM SIN 45 D→R SIN |
|||
π 3 / →NUM COS 60 D→R COS |
|||
e: return, |
|||
π 6 / →NUM TAN 30 D→R TAN |
|||
2.7182818284590452353602874713526624977572470936999595749669676277240766303535 |
|||
{{out}} |
|||
/*Note: the "real: E subroutine returns E's accuracy that */ |
|||
<pre> |
|||
/*matches the current NUMERIC DIGITS, up to 1 million digits.*/ |
|||
6: .707106781187 |
|||
/*If more than 1 million digits are required, be patient. */ |
|||
5: .707106781187 |
|||
4: .499999999997 |
|||
exp: procedure; arg x; ix=x%1; if abs(x-ix)>.5 then ix=ix+sign(x); x=x-ix |
|||
3: .499999999997 |
|||
z=1; _=1; w=z; do j=1; _=_*x/j; z=(z+_)/1; if z==w then leave; w=z; end |
|||
2: .577350269189 |
|||
if z\==0 then z=z*e()**ix; return z |
|||
1: .577350269189 |
|||
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''' |
|||
<pre style="overflow:scroll"> |
|||
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 |
|||
</pre> |
</pre> |
||
As we have now in the stack the 6 values to be inversed, let's call the required functions in reverse order. The <code>6 ROLLD</code> instruction pushes the number from level 1 to level 6 of the stack, making thus the next number available for inversion. |
|||
ATAN R→D 6 ROLLD |
|||
ATAN 6 ROLLD |
|||
ACOS R→D 6 ROLLD |
|||
ACOS 6 ROLLD |
|||
ASIN R→D 6 ROLLD |
|||
ASIN 6 ROLLD |
|||
{{out}} |
|||
<pre> |
|||
6: .785398163397 |
|||
5: 45 |
|||
4: 1.0471975512 |
|||
3: 60.0000000002 |
|||
2: .523598775598 |
|||
1: 30 |
|||
</pre> |
|||
Calculations made with a HP-28S. Emulator has better precision and returns 60 for <code>60 D→R COS ACOS R→D</code> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
Ruby's <tt>Math</tt> module contains all six functions. The functions all accept radians only, so conversion is necessary when dealing with degrees. |
Ruby's <tt>Math</tt> module contains all six functions. The functions all accept radians only, so conversion is necessary when dealing with degrees. |
||
< |
<syntaxhighlight lang="ruby">radians = Math::PI / 4 |
||
degrees = 45.0 |
degrees = 45.0 |
||
Line 2,131: | Line 4,908: | ||
#arctangent |
#arctangent |
||
arctan = Math.atan(Math.tan(radians)) |
arctan = Math.atan(Math.tan(radians)) |
||
puts "#{arctan} #{rad2deg(arctan)}"</ |
puts "#{arctan} #{rad2deg(arctan)}"</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
0.7071067811865475 0.7071067811865475 |
|||
0.707106781187 0.707106781187 |
|||
0.7071067811865476 0.7071067811865476 |
|||
0.707106781187 0.707106781187 |
|||
0.9999999999999999 0.9999999999999999 |
|||
1.0 1.0 |
|||
0.7853981633974482 44.99999999999999 |
|||
0.785398163397 45.0 |
|||
0. |
0.7853981633974483 45.0 |
||
0. |
0.7853981633974483 45.0 |
||
</pre> |
</pre> |
||
Line 2,148: | Line 4,925: | ||
{{trans|bc}} |
{{trans|bc}} |
||
{{works with|Ruby|1.9}} |
{{works with|Ruby|1.9}} |
||
< |
<syntaxhighlight lang="ruby">require 'bigdecimal' # BigDecimal |
||
require 'bigdecimal/math' # BigMath |
require 'bigdecimal/math' # BigMath |
||
Line 2,160: | Line 4,937: | ||
# Arcsine of _y_, domain [-1, 1], range [-pi/2, pi/2]. |
# Arcsine of _y_, domain [-1, 1], range [-pi/2, pi/2]. |
||
def asin(y, prec) |
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 |
end |
||
# Arccosine of _x_, domain [-1, 1], range [0, pi]. |
# Arccosine of _x_, domain [-1, 1], range [0, pi]. |
||
def acos(x, prec) |
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 |
|||
a |
|||
end |
|||
end |
end |
||
Line 2,210: | Line 4,987: | ||
"\n atan(sqrt(3)) = ", |
"\n atan(sqrt(3)) = ", |
||
f[ atan(sqrt(b3, prec), prec) / degrees ], |
f[ atan(sqrt(b3, prec), prec) / degrees ], |
||
"\n")</ |
"\n")</syntaxhighlight> |
||
{{out}} |
|||
Output: <pre>Using radians: |
|||
<pre> |
|||
Using radians: |
|||
sin(-pi / 6) = -0.5 |
sin(-pi / 6) = -0.5 |
||
cos(3 * pi / 4) = -0.70710678118654752440084436210484903928483593768847 |
cos(3 * pi / 4) = -0.70710678118654752440084436210484903928483593768847 |
||
Line 2,225: | Line 5,004: | ||
asin(-1 / 2) = -30.0 |
asin(-1 / 2) = -30.0 |
||
acos(-sqrt(2) / 2) = 135.0 |
acos(-sqrt(2) / 2) = 135.0 |
||
atan(sqrt(3)) = 60.0 |
atan(sqrt(3)) = 60.0 |
||
</pre> |
|||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
<syntaxhighlight lang="runbasic">' Find these three ratios: Sine, Cosine, Tangent. (These ratios have NO units.) |
|||
<lang runbasic>deg = 45.0 |
|||
' Run BASIC works in radians. Convert deg and rad as shown. |
|||
d2r = ACS(-1)/180 |
|||
rad = deg*d2r |
|||
r2d = 180/ACS(-1) |
|||
deg = 45.0 |
|||
print "Sine: ";SIN(rad);" ";SIN(deg*d2r) |
|||
' Run BASIC works in radians; so, first convert deg to rad as shown in next line. |
|||
print "Cosine: ";COS(rad);" ";COS(deg*d2r) |
|||
rad = deg * (atn(1)/45) |
|||
print "Tangent: ";TAN(rad);" ";TAN(deg*d2r) |
|||
print "Ratios for a "; deg; " degree angle, (or "; rad; " radian angle.)" |
|||
print |
|||
print " |
print "Sine: "; SIN(rad) |
||
print " |
print "Cosine: "; COS(rad) |
||
print "Tangent: "; TAN(rad) |
|||
print "Arctangent: ";ATN(TAN(rad));" radians, (or ";ATN(TAN(deg*d2r))*r2d;" degrees)"</lang>Output: |
|||
<pre>Sine: 0.707106781 0.707106781 |
|||
Cosine: 0.707106781 0.707106781 |
|||
Tangent: 1.0 1.0 |
|||
print "Inverse Functions - - (Using above ratios)" |
|||
' Now, use those ratios to work backwards to show their original angle in radians. |
|||
' Also, use this: rad / (atn(1)/45) = deg (To change radians to degrees.) |
|||
print "Arcsine: "; ASN(SIN(rad)); " radians, (or "; ASN(SIN(rad))/(atn(1)/45); " degrees)" |
|||
print "Arccosine: "; ACS(COS(rad)); " radians, (or "; ACS(COS(rad))/(atn(1)/45); " degrees)" |
|||
print "Arctangent: "; ATN(TAN(rad)); " radians, (or "; ATN(TAN(rad))/(atn(1)/45); " degrees)" |
|||
' This code also works in Liberty BASIC. |
|||
' The above (atn(1)/45) = approx .01745329252</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Ratios for a 45.0 degree angle, (or 0.785398163 radian angle.) |
|||
Sine: 0.707106781 |
|||
Cosine: 0.707106781 |
|||
Tangent: 1.0 |
|||
Inverse Functions - - (Using above ratios) |
|||
Arcsine: 0.785398163 radians, (or 45.0 degrees) |
Arcsine: 0.785398163 radians, (or 45.0 degrees) |
||
Arccosine: 0.785398163 radians, (or 45.0 degrees) |
Arccosine: 0.785398163 radians, (or 45.0 degrees) |
||
Arctangent: 0.785398163 radians, (or 45.0 degrees)</pre> |
Arctangent: 0.785398163 radians, (or 45.0 degrees)</pre> |
||
=={{header|Rust}}== |
|||
{{trans|Perl}} |
|||
<syntaxhighlight lang="rust">// 20210221 Rust programming solution |
|||
use std::f64::consts::PI; |
|||
fn main() { |
|||
let angle_radians: f64 = PI/4.0; |
|||
let angle_degrees: f64 = 45.0; |
|||
println!("{} {}", angle_radians.sin(), angle_degrees.to_radians().sin()); |
|||
println!("{} {}", angle_radians.cos(), angle_degrees.to_radians().cos()); |
|||
println!("{} {}", angle_radians.tan(), angle_degrees.to_radians().tan()); |
|||
let asin = angle_radians.sin().asin(); |
|||
println!("{} {}", asin, asin.to_degrees()); |
|||
let acos = angle_radians.cos().acos(); |
|||
println!("{} {}", acos, acos.to_degrees()); |
|||
let atan = angle_radians.tan().atan(); |
|||
println!("{} {}", atan, atan.to_degrees()); |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0.7071067811865475 0.7071067811865475 |
|||
0.7071067811865476 0.7071067811865476 |
|||
0.9999999999999999 0.9999999999999999 |
|||
0.7853981633974482 44.99999999999999 |
|||
0.7853981633974483 45 |
|||
0.7853981633974483 45 |
|||
</pre> |
|||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
< |
<syntaxhighlight lang="sas">data _null_; |
||
pi = 4*atan(1); |
pi = 4*atan(1); |
||
deg = 30; |
deg = 30; |
||
Line 2,280: | Line 5,100: | ||
b=atan(x)/k; |
b=atan(x)/k; |
||
put a b; |
put a b; |
||
run;</ |
run;</syntaxhighlight> |
||
=={{header| |
=={{header|Scala}}== |
||
{{libheader|Scala}}<syntaxhighlight lang="scala">import scala.math._ |
|||
object Gonio extends App { |
|||
<lang scheme>(define pi (* 4 (atan 1))) |
|||
//Pi / 4 rad is 45 degrees. All answers should be the same. |
|||
val radians = Pi / 4 |
|||
val degrees = 45.0 |
|||
println(s"${sin(radians)} ${sin(toRadians(degrees))}") |
|||
//cosine |
|||
println(s"${cos(radians)} ${cos(toRadians(degrees))}") |
|||
//tangent |
|||
println(s"${tan(radians)} ${tan(toRadians(degrees))}") |
|||
//arcsine |
|||
val bgsin = asin(sin(radians)) |
|||
println(s"$bgsin ${toDegrees(bgsin)}") |
|||
val bgcos = acos(cos(radians)) |
|||
println(s"$bgcos ${toDegrees(bgcos)}") |
|||
//arctangent |
|||
val bgtan = atan(tan(radians)) |
|||
println(s"$bgtan ${toDegrees(bgtan)}") |
|||
val bgtan2 = atan2(1, 1) |
|||
println(s"$bgtan ${toDegrees(bgtan)}") |
|||
}</syntaxhighlight> |
|||
=={{header|Scheme}}== |
|||
<syntaxhighlight lang="scheme">(define pi (* 4 (atan 1))) |
|||
(define radians (/ pi 4)) |
(define radians (/ pi 4)) |
||
Line 2,320: | Line 5,164: | ||
(display " ") |
(display " ") |
||
(display (* arctan (/ 180 pi))) |
(display (* arctan (/ 180 pi))) |
||
(newline)</ |
(newline)</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
Line 2,332: | Line 5,176: | ||
[http://seed7.sourceforge.net/libraries/math.htm#atan%28ref_float%29 atan]. |
[http://seed7.sourceforge.net/libraries/math.htm#atan%28ref_float%29 atan]. |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "float.s7i"; |
include "float.s7i"; |
||
include "math.s7i"; |
include "math.s7i"; |
||
Line 2,348: | Line 5,192: | ||
writeln("arccosine: " <& acos(0.70710677) digits 5 <& acos(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); |
writeln("arctangent: " <& atan(1.0) digits 5 <& atan(1.0) * 180.0 / PI digits 5 lpad 9); |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
radians degrees |
radians degrees |
||
Line 2,360: | Line 5,204: | ||
arctangent: 0.78540 45.00000 |
arctangent: 0.78540 45.00000 |
||
</pre> |
</pre> |
||
=={{header|Sidef}}== |
|||
<syntaxhighlight lang="ruby">var angle_deg = 45; |
|||
var angle_rad = Num.pi/4; |
|||
for arr in [ |
|||
[sin(angle_rad), sin(deg2rad(angle_deg))], |
|||
[cos(angle_rad), cos(deg2rad(angle_deg))], |
|||
[tan(angle_rad), tan(deg2rad(angle_deg))], |
|||
[cot(angle_rad), cot(deg2rad(angle_deg))], |
|||
] { |
|||
say arr.join(" "); |
|||
} |
|||
for n in [ |
|||
asin(sin(angle_rad)), |
|||
acos(cos(angle_rad)), |
|||
atan(tan(angle_rad)), |
|||
acot(cot(angle_rad)), |
|||
] { |
|||
say [n, rad2deg(n)].join(' '); |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0.707106781186547 0.707106781186547 |
|||
0.707106781186548 0.707106781186548 |
|||
1 1 |
|||
1 1 |
|||
0.785398163397448 45 |
|||
0.785398163397448 45 |
|||
0.785398163397448 45 |
|||
0.785398163397448 45 |
|||
</pre> |
|||
=={{header|SparForte}}== |
|||
As a structured script. |
|||
<syntaxhighlight lang="ada">#!/usr/local/bin/spar |
|||
pragma annotate( summary, "trig" ) |
|||
@( description, "If your language has a library or built-in " ) |
|||
@( description, "functions for trigonometry, show examples of: ") |
|||
@( description, "sine, cosine, tangent, inverses (of the above) " ) |
|||
@( description, "using the same angle in radians and degrees." ) |
|||
@( description, "" ) |
|||
@( description, "For the non-inverse functions, each radian/" ) |
|||
@( description, "degree pair should use arguments that evaluate to " ) |
|||
@( description, "the same angle (that is, it's not necessary to " ) |
|||
@( description, "use the same angle for all three regular " ) |
|||
@( description, "functions as long as the two sine calls use the " ) |
|||
@( description, "same angle). For the inverse functions, use " ) |
|||
@( description, "the same number and convert its answer to radians " ) |
|||
@( description, "and degrees." ) |
|||
@( category, "tutorials" ) |
|||
@( author, "Ken O. Burtch" ) |
|||
@( see_also, "http://rosettacode.org/wiki/Trigonometric_functions" ); |
|||
pragma license( unrestricted ); |
|||
pragma software_model( nonstandard ); |
|||
pragma restriction( no_external_commands ); |
|||
procedure trig is |
|||
degrees_cycle : constant float := 360.0; |
|||
radians_cycle : constant float := 2.0 * float( numerics.pi ); |
|||
angle_degrees : constant float := 45.0; |
|||
angle_radians : constant float := float( numerics.pi ) / 4.0; |
|||
begin |
|||
put( "Sin " ) |
|||
@( numerics.sin( angle_degrees, degrees_cycle ) ) |
|||
@( numerics.sin( angle_radians, radians_cycle ) ); |
|||
new_line; |
|||
put( "Cos " ) |
|||
@( numerics.cos( angle_degrees, degrees_cycle ) ) |
|||
@( numerics.cos( angle_radians, radians_cycle ) ); |
|||
new_line; |
|||
put( "Tan " ) |
|||
@( numerics.tan( angle_degrees, degrees_cycle ) ) |
|||
@( numerics.tan( angle_radians, radians_cycle ) ); |
|||
new_line; |
|||
put( "Cot " ) |
|||
@( numerics.cot( angle_degrees, degrees_cycle ) ) |
|||
@( numerics.cot( angle_radians, radians_cycle ) ); |
|||
new_line; |
|||
put( "Arcsin" ) |
|||
@( numerics.arcsin( numerics.sin( angle_degrees, degrees_cycle ), degrees_cycle ) ) |
|||
@( numerics.arcsin( numerics.sin( angle_radians, radians_cycle ), radians_cycle ) ); |
|||
new_line; |
|||
put( "Arccos" ) |
|||
@( numerics.arccos( numerics.cos( angle_degrees, degrees_cycle ), degrees_cycle ) ) |
|||
@( numerics.arccos( numerics.cos( angle_radians, radians_cycle ), radians_cycle ) ); |
|||
new_line; |
|||
put( "Arctan" ) |
|||
@( numerics.arctan( numerics.tan( angle_degrees, degrees_cycle ), 1, degrees_cycle ) ) |
|||
@( numerics.arctan( numerics.tan( angle_radians, radians_cycle ), 1, radians_cycle ) ); |
|||
new_line; |
|||
put( "Arccot" ) |
|||
@( numerics.arccot( numerics.cot( angle_degrees, degrees_cycle ), 1, degrees_cycle ) ) |
|||
@( numerics.arccot( numerics.cot( angle_radians, radians_cycle ), 1, radians_cycle ) ); |
|||
new_line; |
|||
command_line.set_exit_status( 0 ); |
|||
end trig;</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
$ spar trig |
|||
Sin 7.07106781186547E-01 7.07106781186547E-01 |
|||
Cos 7.07106781186547E-01 7.07106781186548E-01 |
|||
Tan 1.00000000000000E+00 9.99999999999998E-01 |
|||
Cot 1.00000000000000E+00 1.00000000000000E+00 |
|||
Arcsin 4.50000000000000E+01 7.85398163397448E-01 |
|||
Arccos 4.50000000000000E+01 7.85398163397448E-01 |
|||
Arctan 45 7.85398163397448E-01 |
|||
Arccot 45 7.85398163397449E-01</pre> |
|||
=={{header|SQL PL}}== |
|||
{{works with|Db2 LUW}} |
|||
With SQL only: |
|||
<syntaxhighlight lang="sql pl"> |
|||
--Conversion |
|||
values degrees(3.1415926); |
|||
values radians(180); |
|||
-- This is equal to Pi. |
|||
--PI/4 45 |
|||
values sin(radians(180)/4); |
|||
values sin(radians(45)); |
|||
values cos(radians(180)/4); |
|||
values cos(radians(45)); |
|||
values tan(radians(180)/4); |
|||
values tan(radians(45)); |
|||
values cot(radians(180)/4); |
|||
values cot(radians(45)); |
|||
values asin(sin(radians(180)/4)); |
|||
values asin(sin(radians(45))); |
|||
values atan(tan(radians(180)/4)); |
|||
values atan(tan(radians(45))); |
|||
--PI/3 60 |
|||
values sin(radians(180)/3); |
|||
values sin(radians(60)); |
|||
values cos(radians(180)/3); |
|||
values cos(radians(60)); |
|||
values tan(radians(180)/3); |
|||
values tan(radians(60)); |
|||
values cot(radians(180)/3); |
|||
values cot(radians(60)); |
|||
values asin(sin(radians(180)/3)); |
|||
values asin(sin(radians(60))); |
|||
values atan(tan(radians(180)/3)); |
|||
values atan(tan(radians(60))); |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
db2 -tx |
|||
values degrees(3.1415926) |
|||
+1.79999996929531E+002 |
|||
values radians(180) |
|||
+3.14159265358979E+000 |
|||
values sin(radians(180)/4) |
|||
+7.07106781186547E-001 |
|||
values sin(radians(45)) |
|||
+7.07106781186547E-001 |
|||
values cos(radians(180)/4) |
|||
+7.07106781186548E-001 |
|||
values cos(radians(45)) |
|||
+7.07106781186548E-001 |
|||
values tan(radians(180)/4) |
|||
+1.00000000000000E+000 |
|||
values tan(radians(45)) |
|||
+1.00000000000000E+000 |
|||
values cot(radians(180)/4) |
|||
+1.00000000000000E+000 |
|||
values cot(radians(45)) |
|||
+1.00000000000000E+000 |
|||
values asin(sin(radians(180)/4)) |
|||
+7.85398163397448E-001 |
|||
values asin(sin(radians(45))) |
|||
+7.85398163397448E-001 |
|||
values atan(tan(radians(180)/4)) |
|||
+7.85398163397448E-001 |
|||
values atan(tan(radians(45))) |
|||
+7.85398163397448E-001 |
|||
values sin(radians(180)/3) |
|||
+8.66025403784439E-001 |
|||
values sin(radians(60)) |
|||
+8.66025403784439E-001 |
|||
values cos(radians(180)/3) |
|||
+5.00000000000000E-001 |
|||
values cos(radians(60)) |
|||
+5.00000000000000E-001 |
|||
values tan(radians(180)/3) |
|||
+1.73205080756888E+000 |
|||
values tan(radians(60)) |
|||
+1.73205080756888E+000 |
|||
values cot(radians(180)/3) |
|||
+5.77350269189626E-001 |
|||
values cot(radians(60)) |
|||
+5.77350269189626E-001 |
|||
values asin(sin(radians(180)/3)) |
|||
+1.04719755119660E+000 |
|||
values asin(sin(radians(60))) |
|||
+1.04719755119660E+000 |
|||
values atan(tan(radians(180)/3)) |
|||
+1.04719755119660E+000 |
|||
values atan(tan(radians(60))) |
|||
+1.04719755119660E+000 |
|||
</pre> |
|||
=={{header|Stata}}== |
|||
Stata computes only in radians, but the conversion is easy. |
|||
<syntaxhighlight lang="stata">scalar deg=_pi/180 |
|||
display cos(30*deg) |
|||
display sin(30*deg) |
|||
display tan(30*deg) |
|||
display cos(_pi/6) |
|||
display sin(_pi/6) |
|||
display tan(_pi/6) |
|||
display acos(0.5) |
|||
display asin(0.5) |
|||
display atan(0.5)</syntaxhighlight> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
The built-in functions only take radian arguments. |
The built-in functions only take radian arguments. |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
proc PI {} {expr {4*atan(1)}} |
proc PI {} {expr {4*atan(1)}} |
||
Line 2,380: | Line 5,478: | ||
set arctan [atan [tan $radians]]; puts "$arctan [rad2deg $arctan]" |
set arctan [atan [tan $radians]]; puts "$arctan [rad2deg $arctan]" |
||
} |
} |
||
trig 60.0</ |
trig 60.0</syntaxhighlight> |
||
<pre>0.8660254037844386 |
<pre>0.8660254037844386 |
||
0.5000000000000001 |
0.5000000000000001 |
||
Line 2,387: | Line 5,485: | ||
1.0471975511965976 59.99999999999999 |
1.0471975511965976 59.99999999999999 |
||
1.0471975511965976 59.99999999999999</pre> |
1.0471975511965976 59.99999999999999</pre> |
||
=={{header|VBA}}== |
|||
<syntaxhighlight lang="vb">Public Sub trig() |
|||
Pi = WorksheetFunction.Pi() |
|||
Debug.Print Sin(Pi / 2) |
|||
Debug.Print Sin(90 * Pi / 180) |
|||
Debug.Print Cos(0) |
|||
Debug.Print Cos(0 * Pi / 180) |
|||
Debug.Print Tan(Pi / 4) |
|||
Debug.Print Tan(45 * Pi / 180) |
|||
Debug.Print WorksheetFunction.Asin(1) * 2 |
|||
Debug.Print WorksheetFunction.Asin(1) * 180 / Pi |
|||
Debug.Print WorksheetFunction.Acos(0) * 2 |
|||
Debug.Print WorksheetFunction.Acos(0) * 180 / Pi |
|||
Debug.Print Atn(1) * 4 |
|||
Debug.Print Atn(1) * 180 / Pi |
|||
End Sub</syntaxhighlight>{{out}} |
|||
<pre> 1 |
|||
1 |
|||
1 |
|||
1 |
|||
1 |
|||
1 |
|||
3,14159265358979 |
|||
90 |
|||
3,14159265358979 |
|||
90 |
|||
3,14159265358979 |
|||
45 |
|||
</pre> |
|||
=={{header|Visual Basic .NET}}== |
|||
{{trans|C#}} |
|||
<syntaxhighlight lang="vbnet">Module Module1 |
|||
Sub Main() |
|||
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) |
|||
End Sub |
|||
End Module</syntaxhighlight> |
|||
{{out}} |
|||
<pre>=== radians === |
|||
sin (pi/3) = 0.866025403784439 |
|||
cos (pi/3) = 0.5 |
|||
tan (pi/3) = 1.73205080756888 |
|||
arcsin (1/2) = 0.523598775598299 |
|||
arccos (1/2) = 1.0471975511966 |
|||
arctan (1/2) = 0.463647609000806 |
|||
=== degrees === |
|||
sin (60) = 0.866025403784439 |
|||
cos (60) = 0.5 |
|||
tan (60) = 1.73205080756888 |
|||
arcsin (1/2) = 30 |
|||
arccos (1/2) = 60 |
|||
arctan (1/2) = 26.565051177078</pre> |
|||
=={{header|Wren}}== |
|||
{{trans|Go}} |
|||
{{libheader|Wren-fmt}} |
|||
<syntaxhighlight lang="wren">import "./fmt" for Fmt |
|||
var d = 30 |
|||
var r = d * Num.pi / 180 |
|||
var s = 0.5 |
|||
var c = 3.sqrt / 2 |
|||
var t = 1 / 3.sqrt |
|||
Fmt.print("sin($9.6f deg) = $f", d, (d*Num.pi/180).sin) |
|||
Fmt.print("sin($9.6f rad) = $f", r, r.sin) |
|||
Fmt.print("cos($9.6f deg) = $f", d, (d*Num.pi/180).cos) |
|||
Fmt.print("cos($9.6f rad) = $f", r, r.cos) |
|||
Fmt.print("tan($9.6f deg) = $f", d, (d*Num.pi/180).tan) |
|||
Fmt.print("tan($9.6f rad) = $f", r, r.tan) |
|||
Fmt.print("asin($f) = $9.6f deg", s, s.asin*180/Num.pi) |
|||
Fmt.print("asin($f) = $9.6f rad", s, s.asin) |
|||
Fmt.print("acos($f) = $9.6f deg", c, c.acos*180/Num.pi) |
|||
Fmt.print("acos($f) = $9.6f rad", c, c.acos) |
|||
Fmt.print("atan($f) = $9.6f deg", t, t.atan*180/Num.pi) |
|||
Fmt.print("atan($f) = $9.6f rad", t, t.atan)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
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 |
|||
</pre> |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations |
||
def Pi = 3.14159265358979323846; |
def Pi = 3.14159265358979323846; |
||
Line 2,415: | Line 5,623: | ||
RlOut(0, ACos(B)); ChOut(0, 9\tab\); RlOut(0, Deg(ACos(B))); 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); |
RlOut(0, ATan(C)); ChOut(0, 9\tab\); RlOut(0, Deg(ATan(C))); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
0.50000 0.50000 |
0.50000 0.50000 |
||
Line 2,425: | Line 5,633: | ||
0.52360 30.00000 |
0.52360 30.00000 |
||
0.78540 45.00000 |
0.78540 45.00000 |
||
</pre> |
|||
=={{header|zkl}}== |
|||
<syntaxhighlight lang="zkl"> |
|||
(30.0).toRad().sin() //-->0.5 |
|||
(60.0).toRad().cos() //-->0.5 |
|||
(45.0).toRad().tan() //-->1 |
|||
(0.523599).sin() //-->0.5 |
|||
etc |
|||
(0.5).asin() //-->0.523599 |
|||
(0.5).acos() //-->1.0472 |
|||
(1.0).atan() //-->0.785398 |
|||
(1.0).atan().toDeg() //-->45 |
|||
etc</syntaxhighlight> |
|||
=={{header|ZX Spectrum Basic}}== |
|||
The ZX Spectrum ROM only calculates sine and arctangent directly (via Chebyshev polynomials), and uses internal functions of these (and the square root) to generate the other functions. In particular, arcsin x is calculated as arctan ( x / ( sqrt ( 1 - x * x ) ) + 1 ) / 2, which is why some of these functions are legendarily slow. |
|||
<syntaxhighlight lang="zxbasic">10 DEF FN d(a)=a*PI/180:REM convert degrees to radians; all ZX Spectrum trig calculations are done in radians |
|||
20 DEF FN i(r)=180*r/PI:REM convert radians to degrees for inverse functions |
|||
30 LET d=45 |
|||
40 LET r=PI/4 |
|||
50 PRINT SIN r,SIN FN d(d) |
|||
60 PRINT COS r,COS FN d(d) |
|||
70 PRINT TAN r,TAN FN d(d) |
|||
80 PRINT |
|||
90 LET d=.5 |
|||
110 PRINT ASN d,FN i(ASN d) |
|||
120 PRINT ACS d,FN i(ACS d) |
|||
130 PRINT ATN d,FN i(ATN d)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
0.70710678 0.70710678 |
|||
0.70710678 0.70710678 |
|||
1 1 |
|||
0.52359878 30 |
|||
1.0471976 60 |
|||
0.46364761 26.565051 |
|||
0 OK, 130:1 |
|||
</pre> |
</pre> |
||
Line 2,430: | Line 5,679: | ||
{{omit from|M4}} |
{{omit from|M4}} |
||
[[Category: |
[[Category:Geometry]] |
Latest revision as of 19:39, 14 February 2024
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
If your language has a library or built-in functions for trigonometry, show examples of:
- sine
- cosine
- tangent
- inverses (of the above)
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.
11l
V rad = math:pi / 4
V deg = 45.0
print(‘Sine: ’sin(rad)‘ ’sin(radians(deg)))
print(‘Cosine: ’cos(rad)‘ ’cos(radians(deg)))
print(‘Tangent: ’tan(rad)‘ ’tan(radians(deg)))
V arcsine = asin(sin(rad))
print(‘Arcsine: ’arcsine‘ ’degrees(arcsine))
V arccosine = acos(cos(rad))
print(‘Arccosine: ’arccosine‘ ’degrees(arccosine))
V arctangent = atan(tan(rad))
print(‘Arctangent: ’arctangent‘ ’degrees(arctangent))
- Output:
Sine: 0.707106781 0.707106781 Cosine: 0.707106781 0.707106781 Tangent: 1 1 Arcsine: 0.785398163 45 Arccosine: 0.785398163 45 Arctangent: 0.785398163 45
ACL2
(This doesn't have the inverse functions; the Taylor series for those take too long to converge.)
(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 "~%")))
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.
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);
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).
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;
- 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
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))
)
- 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
ALGOL W
begin
% Algol W only supplies sin, cos and arctan as standard. We can define %
% arcsin, arccos and tan functions using these. The standard functions %
% use radians so we also provide versions that use degrees %
% convert degrees to radians %
real procedure toRadians( real value x ) ; pi * ( x / 180 );
% convert radians to degrees %
real procedure toDegrees( real value x ) ; 180 * ( x / pi );
% tan of an angle in radians %
real procedure tan( real value x ) ; sin( x ) / cos( x );
% arcsin in radians %
real procedure arcsin( real value x ) ; arctan( x / sqrt( 1 - ( x * x ) ) );
% arccos in radians %
real procedure arccos( real value x ) ; arctan( sqrt( 1 - ( x * x ) ) / x );
% sin of an angle in degrees %
real procedure sinD( real value x ) ; sin( toRadians( x ) );
% cos of an angle in degrees %
real procedure cosD( real value x ) ; cos( toRadians( x ) );
% tan of an angle in degrees %
real procedure tanD( real value x ) ; tan( toRadians( x ) );
% arctan in degrees %
real procedure arctanD( real value x ) ; toDegrees( arctan( x ) );
% arcsin in degrees %
real procedure arcsinD( real value x ) ; toDegrees( arcsin( x ) );
% arccos in degrees %
real procedure arccosD( real value x ) ; toDegrees( arccos( x ) );
% test the procedures %
begin
real piOver4, piOver3, oneOverRoot2, root3Over2;
piOver3 := pi / 3; piOver4 := pi / 4;
oneOverRoot2 := 1.0 / sqrt( 2 ); root3Over2 := sqrt( 3 ) / 2;
r_w := 12; r_d := 5; r_format := "A"; s_w := 0; % set output format %
write( "PI/4: ", piOver4, " 1/root(2): ", oneOverRoot2 );
write();
write( "sin 45 degrees: ", sinD( 45 ), " sin pi/4 radians: ", sin( piOver4 ) );
write( "cos 45 degrees: ", cosD( 45 ), " cos pi/4 radians: ", cos( piOver4 ) );
write( "tan 45 degrees: ", tanD( 45 ), " tan pi/4 radians: ", tan( piOver4 ) );
write();
write( "arcsin( sin( pi/4 radians ) ): ", arcsin( sin( piOver4 ) ) );
write( "arccos( cos( pi/4 radians ) ): ", arccos( cos( piOver4 ) ) );
write( "arctan( tan( pi/4 radians ) ): ", arctan( tan( piOver4 ) ) );
write();
write( "PI/3: ", piOver4, " root(3)/2: ", root3Over2 );
write();
write( "sin 60 degrees: ", sinD( 60 ), " sin pi/3 radians: ", sin( piOver3 ) );
write( "cos 60 degrees: ", cosD( 60 ), " cos pi/3 radians: ", cos( piOver3 ) );
write( "tan 60 degrees: ", tanD( 60 ), " tan pi/3 radians: ", tan( piOver3 ) );
write();
write( "arcsin( sin( 60 degrees ) ): ", arcsinD( sinD( 60 ) ) );
write( "arccos( cos( 60 degrees ) ): ", arccosD( cosD( 60 ) ) );
write( "arctan( tan( 60 degrees ) ): ", arctanD( tanD( 60 ) ) );
end
end.
- Output:
PI/4: 0.78539 1/root(2): 0.70710 sin 45 degrees: 0.70710 sin pi/4 radians: 0.70710 cos 45 degrees: 0.70710 cos pi/4 radians: 0.70710 tan 45 degrees: 1.00000 tan pi/4 radians: 1.00000 arcsin( sin( pi/4 radians ) ): 0.78539 arccos( cos( pi/4 radians ) ): 0.78539 arctan( tan( pi/4 radians ) ): 0.78539 PI/3: 0.78539 root(3)/2: 0.86602 sin 60 degrees: 0.86602 sin pi/3 radians: 0.86602 cos 60 degrees: 0.50000 cos pi/3 radians: 0.50000 tan 60 degrees: 1.73205 tan pi/3 radians: 1.73205 arcsin( sin( 60 degrees ) ): 60.00000 arccos( cos( 60 degrees ) ): 60.00000 arctan( tan( 60 degrees ) ): 60.00000
Arturo
pi: 4*atan 1.0
radians: pi/4
degrees: 45.0
print "sine"
print [sin radians, sin degrees*pi/180]
print "cosine"
print [cos radians, cos degrees*pi/180]
print "tangent"
print [tan radians, tan degrees*pi/180]
print "arcsine"
print [asin sin radians, (asin sin radians)*180/pi]
print "arccosine"
print [acos cos radians, (acos cos radians)*180/pi]
print "arctangent"
print [atan tan radians, (atan tan radians)*180/pi]
- Output:
sine 0.7071067811865475 0.7071067811865475 cosine 0.7071067811865476 0.7071067811865476 tangent 0.9999999999999999 0.9999999999999999 arcsine 0.7853981633974482 44.99999999999999 arccosine 0.7853981633974483 45.0 arctangent 0.7853981633974483 45.0
Asymptote
real pi = 4 * atan(1);
real radian = pi / 4.0;
real angulo = 45.0 * pi / 180;
write("Radians : ", radian);
write("Degrees : ", angulo / pi * 180);
write();
write("Sine : ", sin(radian), sin(angulo));
write("Cosine : ", cos(radian), cos(angulo));
write("Tangent : ", tan(radian), tan(angulo));
write();
real temp = asin(sin(radian));
write("Arc Sine : ", temp, temp * 180 / pi);
temp = acos(cos(radian));
write("Arc Cosine : ", temp, temp * 180 / pi);
temp = atan(tan(radian));
write("Arc Tangent : ", temp, temp * 180 / pi);
- Output:
Radians : 0.785398163397448 Degrees : 45 Sine : 0.707106781186547 0.707106781186547 Cosine : 0.707106781186548 0.707106781186548 Tangent : 1 1 Arc Sine : 0.785398163397448 45 Arc Cosine : 0.785398163397448 45 Arc Tangent : 0.785398163397448 45
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
*/
Autolisp
Autolisp provides (sin x) (cos x) (tan x) and (atan x). Function arguments are expressed in radians.
(defun rad_to_deg (rad)(* 180.0 (/ rad PI)))
(defun deg_to_rad (deg)(* PI (/ deg 180.0)))
(defun asin (x)
(cond
((and(> x -1.0)(< x 1.0)) (atan (/ x (sqrt (- 1.0 (* x x))))))
((= x -1.0) (* -1.0 (/ pi 2)))
((= x 1) (/ pi 2))
)
)
(defun acos (x)
(cond
((and(>= x -1.0)(<= x 1.0)) (-(* pi 0.5) (asin x)))
)
)
(list
(list "cos PI/6" (cos (/ pi 6)) "cos 30 deg" (cos (deg_to_rad 30)))
(list "sin PI/4" (sin (/ pi 4)) "sin 45 deg" (sin (deg_to_rad 45)))
(list "tan PI/3" (tan (/ pi 3))"tan 60 deg" (tan (deg_to_rad 60)))
(list "asin 1 rad" (asin 1.0) "asin 1 rad (deg)" (rad_to_deg (asin 1.0)))
(list "acos 1/2 rad" (acos (/ 1 2.0)) "acos 1/2 rad (deg)" (rad_to_deg (acos (/ 1 2.0))))
(list "atan pi/12" (atan (/ pi 12)) "atan 15 deg" (rad_to_deg(atan(deg_to_rad 15))))
)
- Output:
(("cos PI/6 rad" 0.866025 "cos 30 deg" 0.866025) ("sin PI/4 rad" 0.707107 "sin 45 deg" 0.707107) ("tan PI/3 rad" 1.73205 " tan 60 deg" 1.73205) ("asin 1 rad" 1.57080 "asin 1 rad (deg)" 90.0000) ("acos 1/2 rad" 1.04720 "acos 1/2 rad" 60.0000) ("atan pi/12 rad" 0.256053 "atan 15 deg" 14.6707))
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).
# 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
}
- 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
Axe
Axe implements sine, cosine, and inverse tangent natively. One period is [0, 256) and the results are [-127, 127] for maximum precision.
The inverse tangent takes dX and dY parameters, rather than a single argument. This is because it is most often used to calculate angles.
Disp sin(43)▶Dec,i
Disp cos(43)▶Dec,i
Disp tan⁻¹(10,10)▶Dec,i
- Output:
113 68 32
Below is the worked out math.
On a period of 256, an argument of 43 is equivalent to .
Furthermore, and .
So and . Axe uses approximations to calculate the trigonometric functions.
dX and dY values of 10 mean that the angle between them should be . Indeed, the result .
BaCon
' Trigonometric functions in BaCon use Radians for input values
' The RAD() function converts from degrees to radians
FOR v$ IN "0, 10, 45, 90, 190.5"
d = VAL(v$) * 1.0
r = RAD(d) * 1.0
PRINT "Sine: ", d, " degrees (or ", r, " radians) is ", SIN(r)
PRINT "Cosine: ", d, " degrees (or ", r, " radians) is ", COS(r)
PRINT "Tangent: ", d, " degrees (or ", r, " radians) is ", TAN(r)
PRINT
PRINT "Arc Sine: ", SIN(r), " is ", DEG(ASIN(SIN(r))), " degrees (or ", ASIN(SIN(r)), " radians)"
PRINT "Arc CoSine: ", COS(r), " is ", DEG(ACOS(COS(r))), " degrees (or ", ACOS(COS(r)), " radians)"
PRINT "Arc Tangent: ", TAN(r), " is ", DEG(ATN(TAN(r))), " degrees (or ", ATN(TAN(r)), " radians)"
PRINT
NEXT
- Output:
prompt$ bacon -q trigonometric-functions.bac ... Done, program 'trigonometric-functions' ready. prompt$ ./trigonometric-functions Sine: 0 degrees (or 0 radians) is 0 Cosine: 0 degrees (or 0 radians) is 1 Tangent: 0 degrees (or 0 radians) is 0 Arc Sine: 0 is 0 degrees (or 0 radians) Arc CoSine: 1 is 0 degrees (or 0 radians) Arc Tangent: 0 is 0 degrees (or 0 radians) Sine: 10 degrees (or 0.174533 radians) is 0.173648 Cosine: 10 degrees (or 0.174533 radians) is 0.984808 Tangent: 10 degrees (or 0.174533 radians) is 0.176327 Arc Sine: 0.173648 is 10 degrees (or 0.174533 radians) Arc CoSine: 0.984808 is 10 degrees (or 0.174533 radians) Arc Tangent: 0.176327 is 10 degrees (or 0.174533 radians) Sine: 45 degrees (or 0.785398 radians) is 0.707107 Cosine: 45 degrees (or 0.785398 radians) is 0.707107 Tangent: 45 degrees (or 0.785398 radians) is 1 Arc Sine: 0.707107 is 45 degrees (or 0.785398 radians) Arc CoSine: 0.707107 is 45 degrees (or 0.785398 radians) Arc Tangent: 1 is 45 degrees (or 0.785398 radians) Sine: 90 degrees (or 1.5708 radians) is 1 Cosine: 90 degrees (or 1.5708 radians) is 6.12323e-17 Tangent: 90 degrees (or 1.5708 radians) is 16331239353195370 Arc Sine: 1 is 90 degrees (or 1.5708 radians) Arc CoSine: 6.12323e-17 is 90 degrees (or 1.5708 radians) Arc Tangent: 16331239353195370 is 90 degrees (or 1.5708 radians) Sine: 190.5 degrees (or 3.32485 radians) is -0.182236 Cosine: 190.5 degrees (or 3.32485 radians) is -0.983255 Tangent: 190.5 degrees (or 3.32485 radians) is 0.185339 Arc Sine: -0.182236 is -10.5 degrees (or -0.18326 radians) Arc CoSine: -0.983255 is 169.5 degrees (or 2.95833 radians) Arc Tangent: 0.185339 is 10.5 degrees (or 0.18326 radians)
BASIC
QuickBasic 4.5 does not have arcsin and arccos built in. They are defined by identities found here.
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
Applesoft BASIC
The arcsine and arccoscine functions, while not intrinsic to Applesoft BASIC, are calculated using the existing BASIC functions and implemented as FN ASN and FN ACS using the DEF FN function.
100 TAU = 8 * ATN (1)
110 RAD = TAU / 8
120 DEG = 45.0
130 DEF FN RAD(DEG) = DEG * TAU / 360
140 DEF FN DEG(RAD) = RAD / TAU * 360
150 DEF FN ASN(RAD) = ATN (RAD / SQR ( - RAD * RAD + 1))
160 DEF FN ACS(RAD) = - ATN (RAD / SQR ( - RAD * RAD + 1)) + TAU / 4
170 PRINT " SINE: " SIN (RAD);: HTAB (25): PRINT SIN ( FN RAD(DEG))
180 PRINT " COSINE: " COS (RAD);: HTAB (25): PRINT COS ( FN RAD(DEG))
190 PRINT " TANGENT: " TAN (RAD);: HTAB (25): PRINT TAN ( FN RAD(DEG))
200 ARC = FN ASN( SIN (RAD))
210 PRINT " ARCSINE: "ARC;: HTAB (25): PRINT FN DEG(ARC)
220 ARC = FN ACS( COS (RAD))
230 PRINT " ARCCOSINE: "ARC;: HTAB (25): PRINT FN DEG(ARC)
240 ARC = ATN ( TAN (RAD))
250 PRINT " ARCTANGENT: "ARC;: HTAB (25): PRINT FN DEG(ARC);
- Output:
SINE: .707106781 .707106781 COSINE: .707106781 .707106781 TANGENT: 1 1 ARCSINE: .785398163 45 ARCCOSINE: .785398164 45.0000001 ARCTANGENT: .785398163 45
BASIC256
radian = pi / 4
angulo = 45.0 * pi / 180
print "Radians : "; radians(angulo); " ";
print "Degrees : "; degrees(radian)
print
print "Sine : "; sin(radian); " "; sin(angulo)
print "Cosine : "; cos(radian); " "; cos(angulo)
print "Tangent : "; tan(radian); " "; tan(angulo)
print
#temp = asin(sin(radians(angulo)))
temp = asin(sin(radian))
print "Arc Sine : "; temp; " "; degrees(temp)
temp = acos(cos(radian))
print "Arc Cosine : "; temp; " "; degrees(temp)
temp = atan(tan(radian))
print "Arc Tangent : "; temp; " "; degrees(temp)
end
BBC BASIC
@% = &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))
IS-BASIC
100 LET DG=DEG(PI/4)
110 OPTION ANGLE DEGREES
120 PRINT SIN(DG)
130 PRINT COS(DG)
140 PRINT TAN(DG)
150 PRINT ASIN(SIN(DG))
160 PRINT ACOS(COS(DG))
170 PRINT ATN(TAN(DG))
180 LET RD=RAD(45)
190 OPTION ANGLE RADIANS
200 PRINT SIN(RD)
210 PRINT COS(RD)
220 PRINT TAN(RD)
230 PRINT ASIN(SIN(RD))
240 PRINT ACOS(COS(RD))
250 PRINT ATN(TAN(RD))
Yabasic
radians = pi / 4
degrees = 45.0 * pi / 180
tab$ = chr$(09)
print "Radians : ", radians, " ",
print "Degrees : ", degrees / pi * 180
print
print "Sine : ", sin(radians), tab$, sin(degrees)
print "Cosine : ", cos(radians), tab$, cos(degrees)
print "Tangent : ", tan(radians), tab$, tan(degrees)
print
temp = asin(sin(radians))
print "Arc Sine : ", temp, tab$, temp * 180 / pi
temp = acos(cos(radians))
print "Arc Cosine : ", temp, tab$, temp * 180 / pi
temp = atan(tan(radians))
print "Arc Tangent : ", temp, tab$, temp * 180 / pi
end
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
- 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
BQN
BQN has a system value •math
which contains trigonometry functions. Inputs are given in radians. These functions can also be used with BQN's Inverse modifier (⁼
) to get their respective defined inverses.
Some results may be inaccurate due to floating point issues.
The following is done in the BQN REPL:
⟨sin, cos, tan⟩ ← •math
Sin 0
0
Sin π÷2
1
Cos 0
1
Cos π÷2
6.123233995736766e¯17
Tan 0
0
Tan π÷2
16331239353195370
Sin⁼ 0
0
Sin⁼ 1
1.5707963267948966
Cos⁼ 1
0
Cos⁼ 0
1.5707963267948966
Tan⁼ 0
0
Tan⁼ ∞
1.5707963267948966
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;
}
- 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#
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();
}
}
}
C++
#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;
}
Clojure
(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)))
- 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
COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. Trig.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Pi-Third USAGE COMP-2.
01 Degree USAGE COMP-2.
01 60-Degrees USAGE COMP-2.
01 Result USAGE COMP-2.
PROCEDURE DIVISION.
COMPUTE Pi-Third = FUNCTION PI / 3
DISPLAY "Radians:"
DISPLAY " Sin(π / 3) = " FUNCTION SIN(Pi-Third)
DISPLAY " Cos(π / 3) = " FUNCTION COS(Pi-Third)
DISPLAY " Tan(π / 3) = " FUNCTION TAN(Pi-Third)
DISPLAY " Asin(0.5) = " FUNCTION ASIN(0.5)
DISPLAY " Acos(0.5) = " FUNCTION ACOS(0.5)
DISPLAY " Atan(0.5) = " FUNCTION ATAN(0.5)
COMPUTE Degree = FUNCTION PI / 180
COMPUTE 60-Degrees = Degree * 60
DISPLAY "Degrees:"
DISPLAY " Sin(60°) = " FUNCTION SIN(60-Degrees)
DISPLAY " Cos(60°) = " FUNCTION COS(60-Degrees)
DISPLAY " Tan(60°) = " FUNCTION TAN(60-Degrees)
COMPUTE Result = FUNCTION ASIN(0.5) / 60
DISPLAY " Asin(0.5) = " Result
COMPUTE Result = FUNCTION ACOS(0.5) / 60
DISPLAY " Acos(0.5) = " Result
COMPUTE Result = FUNCTION ATAN(0.5) / 60
DISPLAY " Atan(0.5) = " Result
GOBACK
.
- Output:
Radians: Sin(π / 3) = +0.86602540368613976 Cos(π / 3) = +0.50000000017025856 Tan(π / 3) = 1.732050806782486241 Asin(0.5) = +0.52359877559829897 Acos(0.5) = 1.04719755119659785 Atan(0.5) = +0.52359877559829897 Degrees: Sin(60°) = +0.86602538768613932 Cos(60°) = +0.50000002788307131 Tan(60°) = 1.732050678782493636 Asin(0.5) = 0.008726645999999999 Acos(0.5) = 0.017453291999999999 Atan(0.5) = 0.007727460000000000
Common 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))))
D
void main() {
import std.stdio, std.math;
enum degrees = 45.0L;
enum t0 = degrees * PI / 180.0L;
writeln("Reference: 0.7071067811865475244008");
writefln("Sine: %.20f %.20f", PI_4.sin, t0.sin);
writefln("Cosine: %.20f %.20f", PI_4.cos, t0.cos);
writefln("Tangent: %.20f %.20f", PI_4.tan, t0.tan);
writeln;
writeln("Reference: 0.7853981633974483096156");
immutable real t1 = PI_4.sin.asin;
writefln("Arcsine: %.20f %.20f", t1, t1 * 180.0L / PI);
immutable real t2 = PI_4.cos.acos;
writefln("Arccosine: %.20f %.20f", t2, t2 * 180.0L / PI);
immutable real t3 = PI_4.tan.atan;
writefln("Arctangent: %.20f %.20f", t3, t3 * 180.0L / PI);
}
- 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
Delphi
procedure ShowTrigFunctions(Memo: TMemo);
const AngleDeg = 45.0;
var AngleRad,ArcSine,ArcCosine,ArcTangent: double;
begin
AngleRad:=DegToRad(AngleDeg);
Memo.Lines.Add(Format('Angle: Degrees: %3.5f Radians: %3.6f',[AngleDeg,AngleRad]));
Memo.Lines.Add('-------------------------------------------------');
Memo.Lines.Add(Format('Sine: Degrees: %3.6f Radians: %3.6f',[sin(DegToRad(AngleDeg)),sin(AngleRad)]));
Memo.Lines.Add(Format('Cosine: Degrees: %3.6f Radians: %3.6f',[cos(DegToRad(AngleDeg)),cos(AngleRad)]));
Memo.Lines.Add(Format('Tangent: Degrees: %3.6f Radians: %3.6f',[tan(DegToRad(AngleDeg)),tan(AngleRad)]));
ArcSine:=ArcSin(Sin(AngleRad));
Memo.Lines.Add(Format('Arcsine: Degrees: %3.6f Radians: %3.6f',[DegToRad(ArcSine),ArcSine]));
ArcCosine:=ArcCos(cos(AngleRad));
Memo.Lines.Add(Format('Arccosine: Degrees: %3.6f Radians: %3.6f',[DegToRad(ArcCosine),ArcCosine]));
ArcTangent:=ArcTan(tan(AngleRad));
Memo.Lines.Add(Format('Arctangent: Degrees: %3.6f Radians: %3.6f',[DegToRad(ArcTangent),ArcTangent]));
end;
- Output:
Angle: Degrees: 45.00000 Radians: 0.785398 ------------------------------------------------- Sine: Degrees: 0.707107 Radians: 0.707107 Cosine: Degrees: 0.707107 Radians: 0.707107 Tangent: Degrees: 1.000000 Radians: 1.000000 Arcsine: Degrees: 0.013708 Radians: 0.785398 Arccosine: Degrees: 0.013708 Radians: 0.785398 Arctangent: Degrees: 0.013708 Radians: 0.785398 Elapsed Time: 9.118 ms.
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)}
`)
- 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
EasyLang
r = pi / 4
d = 45
#
func r2d r .
return r / pi * 180
.
func d2r d .
return d * pi / 180
.
#
numfmt 4 0
print sin d & " " & sin r2d r
print cos d & " " & cos r2d r
print tan d & " " & tan r2d r
print ""
h = asin sin d
print h & " " & d2r h
h = acos cos d
print h & " " & d2r h
h = atan tan d
print h & " " & d2r h
- Output:
0.7071 0.7071 0.7071 0.7071 1.0000 1.0000 45.0000 0.7854 45 0.7854 45 0.7854
Elena
ELENA 4.x:
import system'math;
import extensions;
public program()
{
console.printLine("Radians:");
console.printLine("sin(π/3) = ",(Pi_value/3).sin());
console.printLine("cos(π/3) = ",(Pi_value/3).cos());
console.printLine("tan(π/3) = ",(Pi_value/3).tan());
console.printLine("arcsin(1/2) = ",0.5r.arcsin());
console.printLine("arccos(1/2) = ",0.5r.arccos());
console.printLine("arctan(1/2) = ",0.5r.arctan());
console.printLine();
console.printLine("Degrees:");
console.printLine("sin(60º) = ",60.0r.Radian.sin());
console.printLine("cos(60º) = ",60.0r.Radian.cos());
console.printLine("tan(60º) = ",60.0r.Radian.tan());
console.printLine("arcsin(1/2) = ",0.5r.arcsin().Degree,"º");
console.printLine("arccos(1/2) = ",0.5r.arccos().Degree,"º");
console.printLine("arctan(1/2) = ",0.5r.arctan().Degree,"º");
console.readChar()
}
Elixir
iex(61)> deg = 45
45
iex(62)> rad = :math.pi / 4
0.7853981633974483
iex(63)> :math.sin(deg * :math.pi / 180) == :math.sin(rad)
true
iex(64)> :math.cos(deg * :math.pi / 180) == :math.cos(rad)
true
iex(65)> :math.tan(deg * :math.pi / 180) == :math.tan(rad)
true
iex(66)> temp = :math.acos(:math.cos(rad))
0.7853981633974483
iex(67)> temp * 180 / :math.pi == deg
true
iex(68)> temp = :math.atan(:math.tan(rad))
0.7853981633974483
iex(69)> temp * 180 / :math.pi == deg
true
Erlang
Deg=45.
Rad=math:pi()/4.
math:sin(Deg * math:pi() / 180)==math:sin(Rad).
- Output:
true
math:cos(Deg * math:pi() / 180)==math:cos(Rad).
- Output:
true
math:tan(Deg * math:pi() / 180)==math:tan(Rad).
- Output:
true
Temp = math:acos(math:cos(Rad)).
Temp * 180 / math:pi()==Deg.
- Output:
true
Temp = math:atan(math:tan(Rad)).
Temp * 180 / math:pi()==Deg.
- Output:
true
F#
open NUnit.Framework
open FsUnit
// radian
[<Test>]
let ``Verify that sin pi returns 0`` () =
let x = System.Math.Sin System.Math.PI
System.Math.Round(x,5) |> should equal 0
[<Test>]
let ``Verify that cos pi returns -1`` () =
let x = System.Math.Cos System.Math.PI
System.Math.Round(x,5) |> should equal -1
[<Test>]
let ``Verify that tan pi returns 0`` () =
let x = System.Math.Tan System.Math.PI
System.Math.Round(x,5) |> should equal 0
[<Test>]
let ``Verify that sin pi/2 returns 1`` () =
let x = System.Math.Sin (System.Math.PI / 2.0)
System.Math.Round(x,5) |> should equal 1
[<Test>]
let ``Verify that cos pi/2 returns -1`` () =
let x = System.Math.Cos (System.Math.PI / 2.0)
System.Math.Round(x,5) |> should equal 0
[<Test>]
let ``Verify that sin pi/3 returns sqrt 3/2`` () =
let actual = System.Math.Sin (System.Math.PI / 3.0)
let expected = System.Math.Round((System.Math.Sqrt 3.0) / 2.0, 5)
System.Math.Round(actual,5) |> should equal expected
[<Test>]
let ``Verify that cos pi/3 returns -1`` () =
let x = System.Math.Cos (System.Math.PI / 3.0)
System.Math.Round(x,5) |> should equal 0.5
[<Test>]
let ``Verify that cos and sin of pi/4 return same value`` () =
let c = System.Math.Cos (System.Math.PI / 4.0)
let s = System.Math.Sin (System.Math.PI / 4.0)
System.Math.Round(c,5) = System.Math.Round(s,5) |> should be True
[<Test>]
let ``Verify that acos pi/3 returns 1/2`` () =
let actual = System.Math.Acos 0.5
let expected = System.Math.Round((System.Math.PI / 3.0),5)
System.Math.Round(actual,5) |> should equal expected
[<Test>]
let ``Verify that asin 1 returns pi/2`` () =
let actual = System.Math.Asin 1.0
let expected = System.Math.Round((System.Math.PI / 2.0),5)
System.Math.Round(actual,5) |> should equal expected
[<Test>]
let ``Verify that atan 0 returns 0`` () =
let actual = System.Math.Atan 0.0
let expected = System.Math.Round(0.0,5)
System.Math.Round(actual,5) |> should equal expected
// degree
let toRadians d = d * System.Math.PI / 180.0
[<Test>]
let ``Verify that pi is 180 degrees`` () =
toRadians 180.0 |> should equal System.Math.PI
[<Test>]
let ``Verify that pi/2 is 90 degrees`` () =
toRadians 90.0 |> should equal (System.Math.PI / 2.0)
[<Test>]
let ``Verify that pi/3 is 60 degrees`` () =
toRadians 60.0 |> should equal (System.Math.PI / 3.0)
[<Test>]
let ``Verify that sin 180 returns 0`` () =
let x = System.Math.Sin (toRadians 180.0)
System.Math.Round(x,5) |> should equal 0
[<Test>]
let ``Verify that cos 180 returns -1`` () =
let x = System.Math.Cos (toRadians 180.0)
System.Math.Round(x,5) |> should equal -1
[<Test>]
let ``Verify that tan 180 returns 0`` () =
let x = System.Math.Tan (toRadians 180.0)
System.Math.Round(x,5) |> should equal 0
[<Test>]
let ``Verify that sin 90 returns 1`` () =
let x = System.Math.Sin (toRadians 90.0)
System.Math.Round(x,5) |> should equal 1
[<Test>]
let ``Verify that cos 90 returns -1`` () =
let x = System.Math.Cos (toRadians 90.0)
System.Math.Round(x,5) |> should equal 0
[<Test>]
let ``Verify that sin 60 returns sqrt 3/2`` () =
let actual = System.Math.Sin (toRadians 60.0)
let expected = System.Math.Round((System.Math.Sqrt 3.0) / 2.0, 5)
System.Math.Round(actual,5) |> should equal expected
[<Test>]
let ``Verify that cos 60 returns -1`` () =
let x = System.Math.Cos (toRadians 60.0)
System.Math.Round(x,5) |> should equal 0.5
[<Test>]
let ``Verify that cos and sin of 45 return same value`` () =
let c = System.Math.Cos (toRadians 45.0)
let s = System.Math.Sin (toRadians 45.0)
System.Math.Round(c,5) = System.Math.Round(s,5) |> should be True
Factor
USING: kernel math math.constants math.functions math.trig
prettyprint ;
pi 4 / 45 deg>rad [ sin ] [ cos ] [ tan ]
[ [ . ] compose dup compose ] tri@ 2tri
.5 [ asin ] [ acos ] [ atan ] tri [ dup rad>deg [ . ] bi@ ] tri@
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.
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)
}
}
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] )
Fortran
Trigonometic functions expect arguments in radians so degrees require conversion
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
- 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
ATAN2(y,x) ! Arctangent(y/x), ''-pi < result <= +pi''
SINH(x) ! Hyperbolic sine
COSH(x) ! Hyperbolic cosine
TANH(x) ! Hyperbolic tangent
But, for those with access to fatter Fortran function libraries, trigonometrical functions working in degrees are also available.
Calculate various trigonometric functions from the Fortran library.
INTEGER BIT(32),B,IP !Stuff for bit fiddling.
INTEGER ENUFF,I !Step through the test angles.
PARAMETER (ENUFF = 17) !A selection of special values.
INTEGER ANGLE(ENUFF) !All in whole degrees.
DATA ANGLE/0,30,45,60,90,120,135,150,180, !Here they are.
1 210,225,240,270,300,315,330,360/ !Thus check angle folding.
REAL PI,DEG2RAD !Special numbers.
REAL D,R,FD,FR,AD,AR !Degree, Radian, F(D), F(R), inverses.
PI = 4*ATAN(1.0) !SINGLE PRECISION 1·0.
DEG2RAD = PI/180 !Limited precision here too for a transcendental number.
Case the first: sines.
WRITE (6,10) ("Sin", I = 1,4) !Supply some names.
10 FORMAT (" Deg.",A7,"(Deg)",A7,"(Rad) Rad - Deg", !Ah, layout.
1 6X,"Arc",A3,"D",6X,"Arc",A3,"R",9X,"Diff")
DO I = 1,ENUFF !Step through the test values.
D = ANGLE(I) !The angle in degrees, in floating point.
R = D*DEG2RAD !Approximation, in radians.
FD = SIND(D); AD = ASIND(FD) !Functions working in degrees.
FR = SIN(R); AR = ASIN(FR)/DEG2RAD !Functions working in radians.
WRITE (6,11) INT(D),FD,FR,FR - FD,AD,AR,AR - AD !Results.
11 FORMAT (I4,":",3F12.8,3F13.7) !Ah, alignment with FORMAT 10...
END DO !On to the next test value.
Case the second: cosines.
WRITE (6,10) ("Cos", I = 1,4)
DO I = 1,ENUFF
D = ANGLE(I)
R = D*DEG2RAD
FD = COSD(D); AD = ACOSD(FD)
FR = COS(R); AR = ACOS(FR)/DEG2RAD
WRITE (6,11) INT(D),FD,FR,FR - FD,AD,AR,AR - AD
END DO
Case the third: tangents.
WRITE (6,10) ("Tan", I = 1,4)
DO I = 1,ENUFF
D = ANGLE(I)
R = D*DEG2RAD
FD = TAND(D); AD = ATAND(FD)
FR = TAN(R); AR = ATAN(FR)/DEG2RAD
WRITE (6,11) INT(D),FD,FR,FR - FD,AD,AR,AR - AD
END DO
WRITE (6,*) "...Special deal for 90 degrees..."
D = 90
R = D*DEG2RAD
FD = TAND(D); AD = ATAND(FD)
FR = TAN(R); AR = ATAN(FR)/DEG2RAD
WRITE (6,*) "TanD =",FD,"Atan =",AD
WRITE (6,*) "TanR =",FR,"Atan =",AR
Convert PI to binary...
PI = PI - 3 !I know it starts with three, and I need the fractional part.
BIT(1:2) = 1 !So, the binary is 11. something.
B = 2 !Two bits known.
DO I = 1,26 !For single precision, more than enough additional bits.
PI = PI*2 !Hoist a bit to the hot spot.
IP = PI !The integral part.
PI = PI - IP !Remove it from the work in progress.
B = B + 1 !Another bit bitten.
BIT(B) = IP !Place it.
END DO !On to the next.
WRITE (6,20) BIT(1:B) !Reveal the bits.
20 FORMAT (" Pi ~ ",2I1,".",66I1) !A known format.
WRITE (6,*) " = 11.00100100001111110110101010001000100001..." !But actually...
END !So much for that.
Output:
Deg. Sin(Deg) Sin(Rad) Rad - Deg ArcSinD ArcSinR Diff 0: 0.00000000 0.00000000 0.00000000 0.0000000 0.0000000 0.0000000 30: 0.50000000 0.50000000 0.00000000 30.0000000 30.0000000 0.0000000 45: 0.70710677 0.70710677 0.00000000 45.0000000 45.0000000 0.0000000 60: 0.86602539 0.86602545 0.00000006 60.0000000 60.0000038 0.0000038 90: 1.00000000 1.00000000 0.00000000 90.0000000 90.0000000 0.0000000 120: 0.86602539 0.86602539 0.00000000 60.0000000 60.0000000 0.0000000 135: 0.70710677 0.70710677 0.00000000 45.0000000 45.0000000 0.0000000 150: 0.50000000 0.50000006 0.00000006 30.0000000 30.0000038 0.0000038 180: 0.00000000 -0.00000009 -0.00000009 0.0000000 -0.0000050 -0.0000050 210: -0.50000000 -0.49999997 0.00000003 -30.0000000 -29.9999981 0.0000019 225: -0.70710677 -0.70710671 0.00000006 -45.0000000 -44.9999962 0.0000038 240: -0.86602539 -0.86602545 -0.00000006 -60.0000000 -60.0000038 -0.0000038 270: -1.00000000 -1.00000000 0.00000000 -90.0000000 -90.0000000 0.0000000 300: -0.86602539 -0.86602545 -0.00000006 -60.0000000 -60.0000038 -0.0000038 315: -0.70710677 -0.70710689 -0.00000012 -45.0000000 -45.0000076 -0.0000076 330: -0.50000000 -0.50000018 -0.00000018 -30.0000000 -30.0000114 -0.0000114 360: 0.00000000 0.00000017 0.00000017 0.0000000 0.0000100 0.0000100 Deg. Cos(Deg) Cos(Rad) Rad - Deg ArcCosD ArcCosR Diff 0: 1.00000000 1.00000000 0.00000000 0.0000000 0.0000000 0.0000000 30: 0.86602539 0.86602539 0.00000000 30.0000019 30.0000019 0.0000000 45: 0.70710677 0.70710677 0.00000000 45.0000000 45.0000000 0.0000000 60: 0.50000000 0.49999997 -0.00000003 60.0000000 60.0000038 0.0000038 90: 0.00000000 -0.00000004 -0.00000004 90.0000000 90.0000000 0.0000000 120: -0.50000000 -0.50000006 -0.00000006 120.0000000 120.0000076 0.0000076 135: -0.70710677 -0.70710677 0.00000000 135.0000000 135.0000000 0.0000000 150: -0.86602539 -0.86602539 0.00000000 150.0000000 150.0000000 0.0000000 180: -1.00000000 -1.00000000 0.00000000 180.0000000 180.0000000 0.0000000 210: -0.86602539 -0.86602539 0.00000000 150.0000000 150.0000000 0.0000000 225: -0.70710677 -0.70710683 -0.00000006 135.0000000 135.0000000 0.0000000 240: -0.50000000 -0.49999991 0.00000009 120.0000000 119.9999924 -0.0000076 270: 0.00000000 0.00000001 0.00000001 90.0000000 90.0000000 0.0000000 300: 0.50000000 0.49999991 -0.00000009 60.0000000 60.0000076 0.0000076 315: 0.70710677 0.70710665 -0.00000012 45.0000000 45.0000114 0.0000114 330: 0.86602539 0.86602533 -0.00000006 30.0000019 30.0000095 0.0000076 360: 1.00000000 1.00000000 0.00000000 0.0000000 0.0000000 0.0000000 Deg. Tan(Deg) Tan(Rad) Rad - Deg ArcTanD ArcTanR Diff 0: 0.00000000 0.00000000 0.00000000 0.0000000 0.0000000 0.0000000 30: 0.57735026 0.57735026 0.00000000 30.0000000 30.0000000 0.0000000 45: 1.00000000 1.00000000 0.00000000 45.0000000 45.0000000 0.0000000 60: 1.73205078 1.73205090 0.00000012 60.0000000 60.0000000 0.0000000 90:************************************ 90.0000000 -90.0000000 -180.0000000 120: -1.73205078 -1.73205054 0.00000024 -60.0000000 -59.9999962 0.0000038 135: -1.00000000 -1.00000000 0.00000000 -45.0000000 -45.0000000 0.0000000 150: -0.57735026 -0.57735032 -0.00000006 -30.0000000 -30.0000019 -0.0000019 180: 0.00000000 0.00000009 0.00000009 0.0000000 0.0000050 0.0000050 210: 0.57735026 0.57735026 0.00000000 30.0000000 30.0000000 0.0000000 225: 1.00000000 0.99999988 -0.00000012 45.0000000 44.9999962 -0.0000038 240: 1.73205078 1.73205125 0.00000048 60.0000000 60.0000076 0.0000076 270:************************************ 90.0000000 -90.0000000 -180.0000000 300: -1.73205078 -1.73205113 -0.00000036 -60.0000000 -60.0000038 -0.0000038 315: -1.00000000 -1.00000024 -0.00000024 -45.0000000 -45.0000076 -0.0000076 330: -0.57735026 -0.57735056 -0.00000030 -30.0000000 -30.0000134 -0.0000134 360: 0.00000000 0.00000017 0.00000017 0.0000000 0.0000100 0.0000100 ...Special deal for 90 degrees... TanD = 1.6331778E+16 Atan = 90.00000 TanR = -2.2877332E+07 Atan = -90.00000 Pi ~ 11.00100100001111110110110000 = 11.00100100001111110110101010001000100001...
Notice that the calculations in radians are less accurate. Firstly, pi cannot be represented exactly and secondly, the conversion factor of pi/180 or 180/pi adds further to the error. The degree-based functions obviously can fold their angles using exact arithmetic (though ACosD has surprising trouble with 30°) and so 360° is the same as 0°, unlike the case with radians. TanD(90°) should yield Infinity (but, which sign?) but perhaps this latter-day feature of computer floating-point was not included. In any case, Tan(90° in radians) faces the problem that its parameter will not in fact be pi/2 but some value just over (or under), and likewise with double precision and quadruple precision and any other finite precision.
FreeBASIC
' FB 1.05.0 Win64
Const pi As Double = 4 * Atn(1)
Dim As Double radians = pi / 4
Dim As Double degrees = 45.0 '' equivalent in degrees
Dim As Double temp
Print "Radians : "; radians, " ";
Print "Degrees : "; degrees
Print
Print "Sine : "; Sin(radians), Sin(degrees * pi / 180)
Print "Cosine : "; Cos(radians), Cos(degrees * pi / 180)
Print "Tangent : "; Tan(radians), Tan(degrees * pi / 180)
Print
temp = ASin(Sin(radians))
Print "Arc Sine : "; temp, temp * 180 / pi
temp = ACos(Cos(radians))
Print "Arc Cosine : "; temp, temp * 180 / pi
temp = Atn(Tan(radians))
Print "Arc Tangent : "; temp, temp * 180 / pi
Sleep
- Output:
Radians : 0.7853981633974483 Degrees : 45 Sine : 0.7071067811865475 0.7071067811865475 Cosine : 0.7071067811865476 0.7071067811865476 Tangent : 0.9999999999999999 0.9999999999999999 Arc Sine : 0.7853981633974482 44.99999999999999 Arc Cosine : 0.7853981633974483 45 Arc Tangent : 0.7853981633974483 45
FutureBasic
include "NSLog.incl"
void local fn DoIt
double degrees = 45.0
double radians = degrees * M_PI / 180
NSLog(@"%f, %f",sin(radians),sin(degrees * M_PI / 180))
NSLog(@"%f, %f",cos(radians),cos(degrees * M_PI / 180))
NSLog(@"%f, %f",tan(radians),tan(degrees * M_PI / 180))
NSLog(@"%f, %f",asin(sin(radians)),asin(sin(radians)) * 180 / M_PI)
NSLog(@"%f, %f",acos(cos(radians)),acos(cos(radians)) * 180 / M_PI)
NSLog(@"%f, %f",atan(tan(radians)),atan(tan(radians)) * 180 / M_PI)
end fn
fn DoIt
HandleEvents
- 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
GAP
# GAP has an improved floating-point support since version 4.5
Pi := Acos(-1.0);
# Or use the built-in constant:
Pi := FLOAT.PI;
r := Pi / 5.0;
d := 36;
Deg := x -> x * Pi / 180;
Sin(r); Asin(last);
Sin(Deg(d)); Asin(last);
Cos(r); Acos(last);
Cos(Deg(d)); Acos(last);
Tan(r); Atan(last);
Tan(Deg(d)); Atan(last);
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.
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))
}
- 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
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"
- 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.
fromDegrees :: Floating a => a -> a
fromDegrees deg = deg * pi / 180
toDegrees :: Floating a => a -> a
toDegrees rad = rad * 180 / pi
main :: IO ()
main =
mapM_
print
[ 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)
]
- Output:
0.49999999999999994 0.49999999999999994 0.8660254037844387 0.8660254037844387 0.5773502691896256 0.5773502691896256 0.5235987755982988 29.999999999999996 1.0471975511965976 59.99999999999999 0.46364760900080615 26.56505117707799
HicEst
Translated from Fortran:
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
0.7071067812 0.7071067812
0.7071067812 0.7071067812
1 1
0.7853981634 45
0.7853981634 45
0.7853981634 45
SINH, COSH, TANH, and inverses are available as well.
IDL
deg = 35 ; arbitrary number of degrees
rad = !dtor*deg ; system variables !dtor and !radeg convert between rad and deg
; 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
; the hyperbolic versions exist and behave as expected:
print, sinh(rad) ; etc
; outputs
; 0.649572
;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
; the trig functions behave as expected for complex arguments:
x = complex(1,2)
print,sin(x)
; outputs
; ( 3.16578, 1.95960)
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
- 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:
(1&o. , 2&o. ,: 3&o.) (4 %~ o. 1) , 180 %~ o. 45
0.707107 0.707107
0.707107 0.707107
1 1
Arcsine, arccosine, and arctangent of one-half, in radians and degrees:
([ ,. 180p_1&*) (_1&o. , _2&o. ,: _3&o.) 0.5
0.523599 30
1.0472 60
0.463648 26.5651
The trig
script adds cover functions for the trigonometric operations as well as verbs for converting degrees from radians (dfr
) and radians from degrees (rfd
)
require 'trig'
(sin , cos ,: tan) (1p1 % 4), rfd 45
0.707107 0.707107
0.707107 0.707107
1 1
([ ,. dfr) (arcsin , arccos ,: arctan) 0.5
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.
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));
}
}
- 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.
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));
jq
jq includes the standard C-library trigonometric functions (sin, cos, tan, asin, acos, atan), but they are provided as filters as illustrated in the definition of radians below.
The trigonometric filters only accept radians, so conversion is necessary when dealing with degrees. The constant π can be defined as also shown in the following definition of radians:
# degrees to radians
def radians:
(-1|acos) as $pi | (. * $pi / 180);
def task:
(-1|acos) as $pi
| ($pi / 180) as $degrees
| "Using radians:",
" sin(-pi / 6) = \( (-$pi / 6) | sin )",
" cos(3 * pi / 4) = \( (3 * $pi / 4) | cos)",
" tan(pi / 3) = \( ($pi / 3) | tan)",
" asin(-1 / 2) = \((-1 / 2) | asin)",
" acos(-sqrt(2)/2) = \((-(2|sqrt)/2) | acos )",
" atan(sqrt(3)) = \( 3 | sqrt | atan )",
"Using degrees:",
" sin(-30) = \((-30 * $degrees) | sin)",
" cos(135) = \((135 * $degrees) | cos)",
" tan(60) = \(( 60 * $degrees) | tan)",
" asin(-1 / 2) = \( (-1 / 2) | asin / $degrees)",
" acos(-sqrt(2)/2) = \( (-(2|sqrt) / 2) | acos / $degrees)",
" atan(sqrt(3)) = \( (3 | sqrt) | atan / $degrees)"
;
task
- Output:
Using radians:
sin(-pi / 6) = -0.49999999999999994
cos(3 * pi / 4) = -0.7071067811865475
tan(pi / 3) = 1.7320508075688767
asin(-1 / 2) = -0.5235987755982988
acos(-sqrt(2)/2) = 2.356194490192345
atan(sqrt(3)) = 1.0471975511965979
Using degrees:
sin(-30) = -0.49999999999999994
cos(135) = -0.7071067811865475
tan(60) = 1.7320508075688767
asin(-1 / 2) = -29.999999999999996
acos(-sqrt(2)/2) = 135
atan(sqrt(3)) = 60.00000000000001
Jsish
Like many programming languages that handle trig, Jsish also includes the atan2 function, which was originally added to Fortran to allow disambiguous results when converting from cartesian to polar coordinates, due to the mirror image nature of normal arctan.
To find what methods are supported, jsish supports help for the Math module.
help Math Math.method(...) Commands performing math operations on numbers Methods: abs acos asin atan atan2 ceil cos exp floor log max min pow random round sin sqrt tan
Angles passed to the trigonometric functions expect arguments in radians (Pi by 4 radians being 45 degrees). Degree to radian conversion is shown by multiplying radians by Pi over 180.
Note the inexact nature of floating point approximations.
/* Trig in Jsish */
var x;
;x = Math.PI / 4;
;Math.sin(x);
;Math.cos(x);
;Math.tan(x);
;Math.asin(Math.sin(x)) * 4;
;Math.acos(Math.cos(x)) * 4;
;Math.atan(Math.tan(x));
;Math.atan2(Math.tan(x), 1.0);
;Math.atan2(Math.tan(x), -1.0);
;x = 45.0;
;Math.sin(x * Math.PI / 180);
;Math.cos(x * Math.PI / 180);
;Math.tan(x * Math.PI / 180);
/*
=!EXPECTSTART!=
x = Math.PI / 4 ==> 0.7853981633974483
Math.sin(x) ==> 0.7071067811865475
Math.cos(x) ==> 0.7071067811865476
Math.tan(x) ==> 0.9999999999999999
Math.asin(Math.sin(x)) * 4 ==> 3.141592653589793
Math.acos(Math.cos(x)) * 4 ==> 3.141592653589793
Math.atan(Math.tan(x)) ==> 0.7853981633974483
Math.atan2(Math.tan(x), 1.0) ==> 0.7853981633974483
Math.atan2(Math.tan(x), -1.0) ==> 2.356194490192345
x = 45.0 ==> 45
Math.sin(x * Math.PI / 180) ==> 0.7071067811865475
Math.cos(x * Math.PI / 180) ==> 0.7071067811865476
Math.tan(x * Math.PI / 180) ==> 0.9999999999999999
=!EXPECTEND!=
*/
- Output:
prompt$ jsish --U trigonometric.jsi x = Math.PI / 4 ==> 0.7853981633974483 Math.sin(x) ==> 0.7071067811865475 Math.cos(x) ==> 0.7071067811865476 Math.tan(x) ==> 0.9999999999999999 Math.asin(Math.sin(x)) * 4 ==> 3.141592653589793 Math.acos(Math.cos(x)) * 4 ==> 3.141592653589793 Math.atan(Math.tan(x)) ==> 0.7853981633974483 Math.atan2(Math.tan(x), 1.0) ==> 0.7853981633974483 Math.atan2(Math.tan(x), -1.0) ==> 2.356194490192345 x = 45.0 ==> 45 Math.sin(x * Math.PI / 180) ==> 0.7071067811865475 Math.cos(x * Math.PI / 180) ==> 0.7071067811865476 Math.tan(x * Math.PI / 180) ==> 0.9999999999999999 prompt$ jsish -u trigonometric.jsi [PASS] trigonometric.jsi
Julia
# v0.6.0
rad = π / 4
deg = 45.0
@show rad deg
@show sin(rad) sin(deg2rad(deg))
@show cos(rad) cos(deg2rad(deg))
@show tan(rad) tan(deg2rad(deg))
@show asin(sin(rad)) asin(sin(rad)) |> rad2deg
@show acos(cos(rad)) acos(cos(rad)) |> rad2deg
@show atan(tan(rad)) atan(tan(rad)) |> rad2deg
- Output:
rad = 0.7853981633974483 deg = 45.0 sin(rad) = 0.7071067811865475 sin(deg2rad(deg)) = 0.7071067811865475 cos(rad) = 0.7071067811865476 cos(deg2rad(deg)) = 0.7071067811865476 tan(rad) = 0.9999999999999999 tan(deg2rad(deg)) = 0.9999999999999999 asin(sin(rad)) = 0.7853981633974482 asin(sin(rad)) |> rad2deg = 44.99999999999999 acos(cos(rad)) = 0.7853981633974483 acos(cos(rad)) |> rad2deg = 45.0 atan(tan(rad)) = 0.7853981633974483 atan(tan(rad)) |> rad2deg = 45.0
Kotlin
import kotlin.math.*
fun main() {
fun Double.toDegrees() = this * 180 / PI
val angle = PI / 4
println("angle = $angle rad = ${angle.toDegrees()}°")
val sine = sin(angle)
println("sin(angle) = $sine")
val cosine = cos(angle)
println("cos(angle) = $cosine")
val tangent = tan(angle)
println("tan(angle) = $tangent")
println()
val asin = asin(sine)
println("asin(sin(angle)) = $asin rad = ${asin.toDegrees()}°")
val acos = acos(cosine)
println("acos(cos(angle)) = $acos rad = ${acos.toDegrees()}°")
val atan = atan(tangent)
println("atan(tan(angle)) = $atan rad = ${atan.toDegrees()}°")
}
- Output:
angle = 0.7853981633974483 rad = 45.0° sin(angle) = 0.7071067811865475 cos(angle) = 0.7071067811865476 tan(angle) = 0.9999999999999999 asin(sin(angle)) = 0.7853981633974482 rad = 44.99999999999999° acos(cos(angle)) = 0.7853981633974483 rad = 45.0° atan(tan(angle)) = 0.7853981633974483 rad = 45.0°
Lambdatalk
{def deg2rad {lambda {:d} {* {/ {PI} 180} :d}}}
-> deg2rad
{def rad2deg {lambda {:r} {* {/ 180 {PI}} :r}}}
-> rad2deg
{deg2rad 180}
-> 3.141592653589793 = PI
{rad2deg {PI}}°
-> 180°
{sin {deg2rad 45}}
-> 0.7071067811865475 = PI/4
{cos {deg2rad 45}}
-> 0.7071067811865476 = PI/4
{tan {deg2rad 45}}
-> 0.9999999999999999 = 1
{rad2deg {asin 0.5}}° -> 30.000000000000004°
{rad2deg {acos 0.5}}° -> 60.00000000000001°
{rad2deg {atan 1}}° -> 45°
Liberty BASIC
pi = ACS(-1)
radians = pi / 4.0
rtod = 180 / pi
degrees = radians * rtod
dtor = pi / 180
'LB works in radians, so degrees require conversion
print "Sin: ";SIN(radians);" "; SIN(degrees*dtor)
print "Cos: ";COS(radians);" "; COS(degrees*dtor)
print "Tan: ";TAN(radians);" ";TAN(degrees*dtor)
print "- Inverse functions:"
print "Asn: ";ASN(SIN(radians));" Rad, "; ASN(SIN(degrees*dtor))*rtod;" Deg"
print "Acs: ";ACS(COS(radians));" Rad, "; ACS(COS(degrees*dtor))*rtod;" Deg"
print "Atn: ";ATN(TAN(radians));" Rad, "; ATN(TAN(degrees*dtor))*rtod;" Deg"
- Output:
Sin: 0.70710678 0.70710678 Cos: 0.70710678 0.70710678 Tan: 1.0 1.0 - Inverse functions: Asn: 0.78539816 Rad, 45.0 Deg Acs: 0.78539816 Rad, 45.0 Deg Atn: 0.78539816 Rad, 45.0 Deg
Logo
UCB Logo has sine, cosine, and arctangent; each having variants for degrees or radians.
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
Lhogho has pi defined in its trigonometric functions. Otherwise the same as UCB Logo.
print sin 45
print cos 45
print arctan 1
print radsin pi / 4
print radcos pi / 4
print 4 * radarctan 1
Logtalk
:- object(trignomeric_functions).
:- public(show/0).
show :-
% standard trignomeric functions work with radians
write('sin(pi/4.0) = '), SIN is sin(pi/4.0), write(SIN), nl,
write('cos(pi/4.0) = '), COS is cos(pi/4.0), write(COS), nl,
write('tan(pi/4.0) = '), TAN is tan(pi/4.0), write(TAN), nl,
write('asin(sin(pi/4.0)) = '), ASIN is asin(sin(pi/4.0)), write(ASIN), nl,
write('acos(cos(pi/4.0)) = '), ACOS is acos(cos(pi/4.0)), write(ACOS), nl,
write('atan(tan(pi/4.0)) = '), ATAN is atan(tan(pi/4.0)), write(ATAN), nl,
write('atan2(3,4) = '), ATAN2 is atan2(3,4), write(ATAN2), nl.
:- end_object.
- Output:
?- trignomeric_functions::show.
sin(pi/4.0) = 0.7071067811865475
cos(pi/4.0) = 0.7071067811865476
tan(pi/4.0) = 0.9999999999999999
asin(sin(pi/4.0)) = 0.7853981633974482
acos(cos(pi/4.0)) = 0.7853981633974483
atan(tan(pi/4.0)) = 0.7853981633974483
atan2(3,4) = 0.6435011087932844
yes
Lua
print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4))
Maple
In radians:
sin(Pi/3);
cos(Pi/3);
tan(Pi/3);
- Output:
> sin(Pi/3); 1/2 3 ---- 2 > cos(Pi/3); 1/2 > tan(Pi/3); 1/2 3
The equivalent in degrees with identical output:
with(Units[Standard]):
sin(60*Unit(degree));
cos(60*Unit(degree));
tan(60*Unit(degree));
Note, Maple also has secant, cosecant, and cotangent:
csc(Pi/3);
sec(Pi/3);
cot(Pi/3);
Finally, the inverse trigonometric functions:
arcsin(1);
arccos(1);
arctan(1);
- Output:
> arcsin(1); Pi ---- 2 > arccos(1); 0 > arctan(1); Pi ---- 4
Lastly, Maple also supports the two-argument arctan plus all the hyperbolic trigonometric functions.
Mathematica/Wolfram Language
Sin[1]
Cos[1]
Tan[1]
ArcSin[1]
ArcCos[1]
ArcTan[1]
Sin[90 Degree]
Cos[90 Degree]
Tan[90 Degree]
MATLAB
A full list of built-in trig functions can be found in the MATLAB Documentation.
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
- Output:
>> 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
Maxima
a: %pi / 3;
[sin(a), cos(a), tan(a), sec(a), csc(a), cot(a)];
b: 1 / 2;
[asin(b), acos(b), atan(b), asec(1 / b), acsc(1 / b), acot(b)];
/* Hyperbolic functions are also available */
a: 1 / 2;
[sinh(a), cosh(a), tanh(a), sech(a), csch(a), coth(a)], numer;
[asinh(a), acosh(1 / a), atanh(a), asech(a), acsch(a), acoth(1 / a)], numer;
MAXScript
Maxscript trigonometric functions accept degrees only. The built-ins degToRad and radToDeg allow easy conversion.
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))
Metafont
Metafont has sind
and cosd
, which compute sine and cosine of an angle expressed in degree. We need to define the rest.
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
MiniScript
pi3 = pi/3
degToRad = pi/180
print "sin PI/3 radians = " + sin(pi3)
print "sin 60 degrees = " + sin(60*degToRad)
print "arcsin 0.5 in radians = " + asin(0.5)
print "arcsin 0.5 in degrees = " + asin(0.5)/degToRad
print "cos PI/3 radians = " + cos(pi3)
print "cos 60 degrees = " + cos(60*degToRad)
print "arccos 0.5 in radians = " + acos(0.5)
print "arccos 0.5 in degrees = " + acos(0.5)/degToRad
print "tan PI/3 radians = " + tan(pi3)
print "tan 60 degrees = " + tan(60*degToRad)
print "arctan 0.5 in radians = " + atan(0.5)
print "arctan 0.5 in degrees = " + atan(0.5)/degToRad
- Output:
sin PI/3 radians = 0.866025 sin 60 degrees = 0.866025 arcsin 0.5 in radians = 0.523599 arcsin 0.5 in degrees = 30.0 cos PI/3 radians = 0.5 cos 60 degrees = 0.5 arccos 0.5 in radians = 1.047198 arccos 0.5 in degrees = 60.0 tan PI/3 radians = 1.732051 tan 60 degrees = 1.732051 arctan 0.5 in radians = 0.463648 arctan 0.5 in degrees = 26.565051
МК-61/52
sin С/П Вx cos С/П Вx tg С/П Вx arcsin С/П Вx arccos С/П Вx arctg С/П
Setting the units of angle (degrees, radians, grads) takes care of the switch Р-ГРД-Г.
Modula-2
MODULE Trig;
FROM RealMath IMPORT pi,sin,cos,tan,arctan,arccos,arcsin;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteReal(v : REAL);
VAR buf : ARRAY[0..31] OF CHAR;
BEGIN
RealToStr(v, buf);
WriteString(buf)
END WriteReal;
VAR theta : REAL;
BEGIN
theta := pi / 4.0;
WriteString("theta: ");
WriteReal(theta);
WriteLn;
WriteString("sin: ");
WriteReal(sin(theta));
WriteLn;
WriteString("cos: ");
WriteReal(cos(theta));
WriteLn;
WriteString("tan: ");
WriteReal(tan(theta));
WriteLn;
WriteString("arcsin: ");
WriteReal(arcsin(sin(theta)));
WriteLn;
WriteString("arccos: ");
WriteReal(arccos(cos(theta)));
WriteLn;
WriteString("arctan: ");
WriteReal(arctan(tan(theta)));
WriteLn;
ReadChar
END Trig.
NetRexx
/* NetRexx */
options replace format comments java crossref symbols nobinary utf8
numeric digits 30
parse 'Radians Degrees angle' RADIANS DEGREES ANGLE .;
parse 'sine cosine tangent arcsine arccosine arctangent' SINE COSINE TANGENT ARCSINE ARCCOSINE ARCTANGENT .
trigVals = ''
trigVals[RADIANS, ANGLE ] = (Rexx Math.PI) / 4 -- Pi/4 == 45 degrees
trigVals[DEGREES, ANGLE ] = 45.0
trigVals[RADIANS, SINE ] = (Rexx Math.sin(trigVals[RADIANS, ANGLE]))
trigVals[DEGREES, SINE ] = (Rexx Math.sin(Math.toRadians(trigVals[DEGREES, ANGLE])))
trigVals[RADIANS, COSINE ] = (Rexx Math.cos(trigVals[RADIANS, ANGLE]))
trigVals[DEGREES, COSINE ] = (Rexx Math.cos(Math.toRadians(trigVals[DEGREES, ANGLE])))
trigVals[RADIANS, TANGENT ] = (Rexx Math.tan(trigVals[RADIANS, ANGLE]))
trigVals[DEGREES, TANGENT ] = (Rexx Math.tan(Math.toRadians(trigVals[DEGREES, ANGLE])))
trigVals[RADIANS, ARCSINE ] = (Rexx Math.asin(trigVals[RADIANS, SINE]))
trigVals[DEGREES, ARCSINE ] = (Rexx Math.toDegrees(Math.acos(trigVals[DEGREES, SINE])))
trigVals[RADIANS, ARCCOSINE ] = (Rexx Math.acos(trigVals[RADIANS, COSINE]))
trigVals[DEGREES, ARCCOSINE ] = (Rexx Math.toDegrees(Math.acos(trigVals[DEGREES, COSINE])))
trigVals[RADIANS, ARCTANGENT] = (Rexx Math.atan(trigVals[RADIANS, TANGENT]))
trigVals[DEGREES, ARCTANGENT] = (Rexx Math.toDegrees(Math.atan(trigVals[DEGREES, TANGENT])))
say ' '.right(12)'|' RADIANS.right(17) '|' DEGREES.right(17) '|'
say ANGLE.right(12)'|' trigVals[RADIANS, ANGLE ].format(4, 12) '|' trigVals[DEGREES, ANGLE ].format(4, 12) '|'
say SINE.right(12)'|' trigVals[RADIANS, SINE ].format(4, 12) '|' trigVals[DEGREES, SINE ].format(4, 12) '|'
say COSINE.right(12)'|' trigVals[RADIANS, COSINE ].format(4, 12) '|' trigVals[DEGREES, COSINE ].format(4, 12) '|'
say TANGENT.right(12)'|' trigVals[RADIANS, TANGENT ].format(4, 12) '|' trigVals[DEGREES, TANGENT ].format(4, 12) '|'
say ARCSINE.right(12)'|' trigVals[RADIANS, ARCSINE ].format(4, 12) '|' trigVals[DEGREES, ARCSINE ].format(4, 12) '|'
say ARCCOSINE.right(12)'|' trigVals[RADIANS, ARCCOSINE ].format(4, 12) '|' trigVals[DEGREES, ARCCOSINE ].format(4, 12) '|'
say ARCTANGENT.right(12)'|' trigVals[RADIANS, ARCTANGENT].format(4, 12) '|' trigVals[DEGREES, ARCTANGENT].format(4, 12) '|'
say
return
- Output:
| Radians | Degrees | angle| 0.785398163397 | 45.000000000000 | sine| 0.707106781187 | 0.707106781187 | cosine| 0.707106781187 | 0.707106781187 | tangent| 1.000000000000 | 1.000000000000 | arcsine| 0.785398163397 | 45.000000000000 | arccosine| 0.785398163397 | 45.000000000000 | arctangent| 0.785398163397 | 45.000000000000 |
Nim
import math, strformat
let rad = Pi/4
let deg = 45.0
echo &"Sine: {sin(rad):.10f} {sin(degToRad(deg)):13.10f}"
echo &"Cosine : {cos(rad):.10f} {cos(degToRad(deg)):13.10f}"
echo &"Tangent: {tan(rad):.10f} {tan(degToRad(deg)):13.10f}"
echo &"Arcsine: {arcsin(sin(rad)):.10f} {radToDeg(arcsin(sin(degToRad(deg)))):13.10f}"
echo &"Arccosine: {arccos(cos(rad)):.10f} {radToDeg(arccos(cos(degToRad(deg)))):13.10f}"
echo &"Arctangent: {arctan(tan(rad)):.10f} {radToDeg(arctan(tan(degToRad(deg)))):13.10f}"
- Output:
Sine: 0.7071067812 0.7071067812 Cosine : 0.7071067812 0.7071067812 Tangent: 1.0000000000 1.0000000000 Arcsine: 0.7853981634 45.0000000000 Arccosine: 0.7853981634 45.0000000000 Arctangent: 0.7853981634 45.0000000000
OCaml
OCaml's preloaded Pervasives module contains all six functions. The functions all accept radians only, so conversion is necessary when dealing with degrees.
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);;
- 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
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
- 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)
Oforth
import: math
: testTrigo
| rad deg hyp z |
Pi 4 / ->rad
45.0 ->deg
0.5 ->hyp
System.Out rad sin << " - " << deg asRadian sin << cr
System.Out rad cos << " - " << deg asRadian cos << cr
System.Out rad tan << " - " << deg asRadian tan << cr
printcr
rad sin asin ->z
System.Out z << " - " << z asDegree << cr
rad cos acos ->z
System.Out z << " - " << z asDegree << cr
rad tan atan ->z
System.Out z << " - " << z asDegree << cr
printcr
System.Out hyp sinh << " - " << hyp sinh asinh << cr
System.Out hyp cosh << " - " << hyp cosh acosh << cr
System.Out hyp tanh << " - " << hyp tanh atanh << cr ;
- Output:
0.707106781186547 - 0.707106781186547 0.707106781186548 - 0.707106781186548 1 - 1 0.785398163397448 - 45 0.785398163397448 - 45 0.785398163397448 - 45 0.521095305493747 - 0.5 1.12762596520638 - 0.5 0.46211715726001 - 0.5
ooRexx
rxm.cls 20 March 2014 The distribution of ooRexx contains a function package called rxMath that provides the computation of trigonometric and some other functions. Based on the underlying C-library the precision of the returned values is limited to 16 digits. Close observation show that sometimes the last one to three digits of the returned values are not correct. Many years ago I experimented with implementing these functions in Rexx with its virtually unlimited precision. The rxm class is intended to provide the same functionality as rxMath with no limit on the specified or implied precision. Functions in class rxm and invocation syntax are the same as in the rxMath library. They are implemented as routines which perform the checking of argument values and invoke the corresponding methods. Here is a list of the supported functions and a concise syntax specification. The arguments are represented by these letters: x is the value for which the respective function must be evaluated. b and c for RxCalcPower are base and exponent, respectively. p if specified is the desired precision (number of digits) in the result. It can be any integer from 1 to 999999. See below for the default used. u if specified, is the unit of x given to the trigonometric functions or the unit of the value returned by the Arcus functions. It can be 'R', 'D', or 'G' for radians, degrees, or grades, respectively. See below for the default used. Trigonometric functions: • rxmCos(x[,[p][,u]]) • rxmCotan(x[,[p][,u]]) • rxmSin(x[,[p][,u]]) • rxmTan(x[,[p][,u]]) Arcus functions: • rxmArcCos(x[,[p][,u]]) • rxmArcSin(x[,[p][,u]]) • rxmArcTan(x[,[p][,u]]) Hyperbolic functions: • rxmCosH(x[,p]) • rxmSinH(x[,p]) • rxmTanH(x[,p]) • rxmExp(x[,p]) e**x • rxmLog(x[,p]) Natural logarithm of x • rxmLog10(x[,p]) Brigg's logarithm of x • rxmSqrt(x[,p]) Square root of x • rxmPower(b,c[,p]) b**c • rxmPi([p]) pi to the specified or default precision Values used for p and u if these are omitted in the invocation ============================================================== The directive ::REQUIRES rxm.cls creates an instance of the class .local~my.rxm=.rxm~new(16,"D") which sets the defaults for p=16 and u='D'. These are used when p or u are omitted in a function invocation. They can be changed by changing the respective class attributes as follows: .locaL~my.rxm~precision=50 .locaL~my.rxm~type='R' The current setting of these attributes can be retrieved as follows: .locaL~my.rxm~precision() .locaL~my.rxm~type() While I tried to get full compatibility there remain a few (actually very few) differences: rxCalcTan(90) raises the Syntax condition (will be fixed in the next ooRexx release) rxCalcexp(x) limits x to 709. or so and returns '+infinity' for larger exponents
/* REXX ---------------------------------------------------------------
* show how the functions can be used
* 03.05.2014 Walter Pachl
*--------------------------------------------------------------------*/
Say 'Default precision:' .locaL~my.rxm~precision()
Say 'Default type: ' .locaL~my.rxm~type()
Say 'rxmsin(60) ='rxmsin(60) -- use default precision and type
Say 'rxmsin(1,21,"R")='rxmsin(1,21,'R') -- precision and type specified
Say 'rxmlog(-1) ='rxmlog(-1)
Say 'rxmlog( 0) ='rxmlog( 0)
Say 'rxmlog( 1) ='rxmlog( 1)
Say 'rxmlog( 2) ='rxmlog( 2)
.locaL~my.rxm~precision=50
.locaL~my.rxm~type='R'
Say 'Changed precision:' .locaL~my.rxm~precision()
Say 'Changed type: ' .locaL~my.rxm~type()
Say 'rxmsin(1) ='rxmsin(1) -- use changed precision and type
::requires rxm.cls
- Output:
Default precision: 16 Default type: D rxmsin(60) =0.8660254037844386 rxmsin(1,21,"R")=0.841470984807896506653 rxmlog(-1) =nan rxmlog( 0) =-infinity rxmlog( 1) =0 rxmlog( 2) =0.6931471805599453 Changed precision: 50 Changed type: R rxmsin(1) =0.84147098480789650665250232163029899962256306079837
/********************************************************************
* Package rxm
* implements the functions available in RxMath with high precision
* by computing the values with significantly increased precision
* and rounding the result to the specified precision.
* This started 10 years ago when Vladimir Zabrodsky published his
* Album of Algorithms http://zabrodsky-rexx.byethost18.com/aat/
* Gerard Schildberger suggests on rosettacode.org to use +10 digits
* Rony Flatscher suggested and helped to turn this into an ooRexx class
* Rick McGuire advised on using Use STRICT Arg for argument checking
* Alexander Seik creates this documentation
* Horst Wegscheider helped with reviewing and some improvements
* 12.04.2014 Walter Pachl
* Documentation: see rxmath.pdf in the ooRexx distribution
* and rxm.doc (here)
* 13.04.2014 WP arcsin and arctan commentary corrected (courtesy Horst)
* 13.04.2014 WP improve arctan performance
* 20.04.2014 WP towards completion
* 24.04.2014 WP arcsin verbessert. courtesy Horst Wegscheider
* 28.04.2014 WP run ooRexxDoc
* 11.08.2014 WP replace log algorithm with Vladimir Zabrodsky's code
**********************************************************************/
.local~my.rxm=.rxm~new(16,"D")
::Class rxm Public
::Method init
Expose precision type
Use Arg precision=(digits()),type='D'
::attribute precision set
Expose precision
Use Strict Arg precision=(digits())
::attribute precision get
::attribute type set
Expose type
Use Strict Arg type='R'
::attribute type get
::Method arccos
/***********************************************************************
* Return arccos(x,precision,type) -- with specified precision
* arccos(x) = pi/2 - arcsin(x)
***********************************************************************/
Expose precision type
Use Strict Arg x,xprec=(precision),xtype=(type)
iprec=xprec+10
Numeric Digits iprec
If x=1 Then
r=0
Else Do
r=self~arcsin(x,iprec,'R')
If r='nan' Then
Return r
r=self~pi(iprec)/2 - r
End
Select
When xtype='D' Then
r=r*180/self~pi(iprec)
When xtype='G' Then
r=r*200/self~pi(iprec)
Otherwise
Nop
End
Numeric Digits xprec
Return (r+0)
::Method arcsin
/***********************************************************************
* Return arcsin(x,precision,type) -- with specified precision
* arcsin(x) = x+(x**3)*1/2*3+(x**5)*1*3/2*4*5+(x**7)*1*3*5/2*4*6*7+...
***********************************************************************/
Expose precision type
Use Strict Arg x,xprec=(precision),xtype=(type)
iprec=xprec+10
Numeric Digits iprec
sign=sign(x)
If x<0 Then
x=abs(x)
Select
When abs(x)>1 Then
Return 'nan'
When x=0 Then
r=0
When x=1 Then
r=rxmpi(iprec)/2
When x<0.8 Then Do
o=x
u=1
r=x
Do i=3 By 2 Until ra=r
ra=r
o=o*x*x*(i-2)
u=u*(i-1)*i/(i-2)
r=r+(o/u)
If r=ra Then
r=r+(o/u)/2 /* final touch */
End
End
Otherwise Do
z=x
r=x
o=x
s=x*x
do j=2 by 2;
o=o*s*(j-1)/j;
z=z+o/(j+1);
if z=r then
leave
r=z;
end
/***********************
y=(1-x*x)/4
n=0.5-self~sqrt(y,iprec)
z=self~sqrt(n,iprec)
r=2*self~arcsin(z,xprec)
***********************/
End
End
Select
When xtype='D' Then
r=r*180/self~pi(iprec)
When xtype='G' Then
r=r*200/self~pi(iprec)
Otherwise
Nop
End
Numeric Digits xprec
Return sign*(r+0)
::Method arctan
/***********************************************************************
* Return arctan(x,precision,type) -- with specified precision
* x=0 -> arctan(x) = 0
* If x>0 Then
* x<1 -> arctan(x) = arcsin(x/sqrt(x**2+1))
* x=1 -> arctan(x) = pi/4
* x>1 -> arctan(x) = pi/2-arcsin((1/x)/sqrt((1/x)**2+1))
* Else
* adjust as necessary
***********************************************************************/
Expose precision type
Use Strict Arg x,xprec=(precision),xtype=(type)
iprec=xprec+10
Numeric Digits iprec
Select
When abs(x)<1 Then
r=self~arcsin(x/self~sqrt(1+x**2,iprec),iprec,'R')
When abs(x)=1 Then
r=self~pi(iprec)/4*sign(x)
Otherwise Do
xr=1/abs(x)
r=self~arcsin(xr/self~sqrt(1+xr**2,iprec),iprec,'R')
If x>0 Then
r=self~pi(iprec)/2-r
Else
r=-self~pi(iprec)/2+r
End
End
Select
When xtype='D' Then
r=r*180/self~pi(iprec)
When xtype='G' Then
r=r*200/self~pi(iprec)
Otherwise
Nop
End
Numeric Digits xprec
Return (r+0)
::Method arsinh
/***********************************************************************
* Return arsinh(x,precision,type) -- with specified precision
* arsinh(x) = ln(x+sqrt(x**2+1))
***********************************************************************/
Expose precision
Use Strict Arg x,xprec=(precision)
iprec=xprec+10
Numeric Digits iprec
x2p1=x**2+1
r=self~log(x+self~sqrt(x2p1,iprec),iprec)
Numeric Digits xprec
Return (r+0)
::Method cos
/* REXX *************************************************************
* Return cos(x,precision,type) -- with the specified precision
* cos(x)=sin(x+pi/2)
********************************************************************/
Expose precision type
Use Strict Arg x,xprec=(precision),xtype=(type)
iprec=xprec+10
Numeric Digits iprec
Select
When xtype='R' Then xa=x+self~pi(iprec)/2
When xtype='D' Then xa=x+90
When xtype='G' Then xa=x+100
End
r=self~sin(xa,iprec,xtype)
Numeric Digits xprec
Return (r+0)
::Method cosh
/* REXX ****************************************************************
* Return cosh(x,precision,type) -- with specified precision
* cosh(x) = 1+(x**2/2!)+(x**4/4!)+(x**6/6!)+-...
***********************************************************************/
Expose precision
Use Strict Arg x,xprec=(precision)
iprec=xprec+10
Numeric Digits iprec
o=1
u=1
r=1
Do i=2 By 2 Until ra=r
ra=r
o=o*x*x
u=u*i*(i-1)
r=r+(o/u)
End
Numeric Digits xprec
Return (r+0)
::Method cotan
/* REXX *************************************************************
* Return cotan(x,precision,type) -- with the specified precision
* cot(x)=cos(x)/sin(x)
********************************************************************/
Expose precision type
Use Strict Arg x,xprec=(precision),xtype=(type)
iprec=xprec+10
Numeric Digits iprec
s=self~sin(x,iprec,xtype)
c=self~cos(x,iprec,xtype)
If s=0 Then
Return '+infinity'
r=c/s
Numeric Digits xprec
Return (r+0)
::Method exp
/***********************************************************************
* exp(x,precision) returns e**x -- with specified precision
* exp(x,precision,base) returns base**x -- with specified precision
***********************************************************************/
Expose precision
Use Strict Arg x,xprec=(precision),xbase=''
iprec=xprec+10
Numeric Digits iprec
Numeric Fuzz 3
If xbase<>'' Then Do
Select
When xbase=0 Then Do
Select
When x<0 Then Return '+infinity'
When x=0 Then Return 'nan'
Otherwise Return 0
End
End
When xbase=1 Then Return 1
When xbase<0 Then Do
Select
When x=0 Then Return 1
When datatype(x,'W')=0 Then Return 'nan'
Otherwise Do
r=xbase**x
Numeric Digits xprec
Return r+0
End
End
End
Otherwise
x=x*self~log(xbase,iprec)
End
End
o=1
u=1
r=1
Do i=1 By 1 Until ra=r
ra=r
o=o*x
u=u*i
r=r+(o/u)
End
Numeric Digits xprec
Return (r+0)
::Method log
/***********************************************************************
* log(x,precision) -- returns ln(x) with specified precision
* log(x,precision,base) -- returns blog(x) with specified precision
* Three different series are used for ln(x): x in range 0 to 0.5
* 0.5 to 1.5
* 1.5 to infinity
***********************************************************************/
Expose precision
Use Strict Arg x,xprec=(precision),xbase=''
iprec=xprec+100
Numeric Digits iprec
Select
When x=0 Then Return '-infinity'
When x<0 Then Return 'nan'
When x<1 Then r= -self~Log(1/X,xprec)
Otherwise Do
do M = 0 until (2 ** M) > X; end
M = M - 1
Z = X / (2 ** M)
Zeta = (1 - Z) / (1 + Z)
N = Zeta; Ln = Zeta; Zetasup2 = Zeta * Zeta
do J = 1
N = N * Zetasup2; NewLn = Ln + N / (2 * J + 1)
if NewLn = Ln then Do
r= M * self~LN2P(xprec) - 2 * Ln
Leave
End
Ln = NewLn
end
End
End
If x>0 Then Do
If xbase>'' Then
r=r/self~log(xbase,iprec)
Numeric Digits xprec
r=r+0
End
Return r
::Method ln2p
Parse Arg p
Numeric Digits p+10
If p<=1000 Then
Return self~ln2()
n=1/3
ln=n
zetasup2=1/9
Do j=1
n=n*zetasup2
newln=ln+n/(2*j+1)
If newln=ln Then
Return 2*ln
ln=newln
End
::Method LN2
v=''
v=v||0.69314718055994530941723212145817656807
v=v||5500134360255254120680009493393621969694
v=v||7156058633269964186875420014810205706857
v=v||3368552023575813055703267075163507596193
v=v||0727570828371435190307038623891673471123
v=v||3501153644979552391204751726815749320651
v=v||5552473413952588295045300709532636664265
v=v||4104239157814952043740430385500801944170
v=v||6416715186447128399681717845469570262716
v=v||3106454615025720740248163777338963855069
v=v||5260668341137273873722928956493547025762
v=v||6520988596932019650585547647033067936544
v=v||3254763274495125040606943814710468994650
v=v||6220167720424524529612687946546193165174
v=v||6813926725041038025462596568691441928716
v=v||0829380317271436778265487756648508567407
v=v||7648451464439940461422603193096735402574
v=v||4460703080960850474866385231381816767514
v=v||3866747664789088143714198549423151997354
v=v||8803751658612753529166100071053558249879
v=v||4147295092931138971559982056543928717000
v=v||7218085761025236889213244971389320378439
v=v||3530887748259701715591070882368362758984
v=v||2589185353024363421436706118923678919237
v=v||231467232172053401649256872747782344535348
return V
::Method log10
/***********************************************************************
* Return log10(x,prec) specified precision
***********************************************************************/
Expose precision
Use Strict Arg x,xprec=(precision)
iprec=xprec+10
r=self~log(x,iprec,10)
Numeric Digits xprec
Return (r+0)
::Method pi
/* REXX *************************************************************
* Return pi with the specified precision
********************************************************************/
Expose precision
Use Strict Arg xprec=(precision)
p='3.141592653589793238462643383279502884197169399375'||,
'10582097494459230781640628620899862803482534211706'||,
'79821480865132823066470938446095505822317253594081'||,
'28481117450284102701938521105559644622948954930381'||,
'96442881097566593344612847564823378678316527120190'||,
'91456485669234603486104543266482133936072602491412'||,
'73724587006606315588174881520920962829254091715364'||,
'36789259036001133053054882046652138414695194151160'||,
'94330572703657595919530921861173819326117931051185'||,
'48074462379962749567351885752724891227938183011949'||,
'12983367336244065664308602139494639522473719070217'||,
'98609437027705392171762931767523846748184676694051'||,
'32000568127145263560827785771342757789609173637178'||,
'72146844090122495343014654958537105079227968925892'||,
'35420199561121290219608640344181598136297747713099'||,
'60518707211349999998372978049951059731732816096318'||,
'59502445945534690830264252230825334468503526193118'||,
'81710100031378387528865875332083814206171776691473'||,
'03598253490428755468731159562863882353787593751957'||,
'781857780532171226806613001927876611195909216420199'
If xprec>1000 Then Do /* more than 1000 digits wanted */
iprec=xprec+10 /* internal precision */
Numeric Digits iprec
new=1
a=sqrt(2,iprec)
b=0
p=2+a
Do i=1 By 1 Until p=pi
pi=p
y=self~sqrt(a,iprec)
a1=(y+1/y)/2
b1=y*(b+1)/(b+a)
p=pi*b1*(1+a1)/(1+b1)
a=a1
b=b1
End
End
Numeric Digits xprec
Return (p+0)
::Method power
/***********************************************************************
* power(base,exponent,precision) returns base**exponent
* -- with specified precision
***********************************************************************/
Expose precision
Use Strict Arg b,c,xprec=(precision)
Numeric Digits xprec
rsign=1
If b<0 Then Do /* negative base */
If datatype(c,'W') Then Do /* Exponent is an integer */
If c//2=1 Then /* .. an odd number */
rsign=-1 /* Resuld will be negative */
b=abs(b) /* proceed with positive base */
End
Else Do /* Exponent is not an integer */
-- Say 'for a negative base ('||b')',
-- 'exponent ('c') must be an integer'
Return 'nan' /* Return not a number */
End
End
If c=0 Then Do
If b>=0 Then
r=1
End
Else
r=self~exp(c,xprec,b)
If datatype(r)<>'NUM' Then
Return r
Return rsign*r
::Method sqrt
/* REXX *************************************************************
* Return sqrt(x,precision) -- with the specified precision
********************************************************************/
Expose precision type
Use Strict Arg x,xprec=(precision)
If x<0 Then Do
Return 'nan'
End
iprec=xprec+10
Numeric Digits iprec
r0= x
r = 1
Do i=1 By 1 Until r=r0 | (abs(r*r-x)<10**-iprec)
r0 = r
r = (r + x/r) / 2
End
Numeric Digits xprec
Return (r+0)
::Method sin
/* REXX *************************************************************
* Return sin(x,precision,type) -- with the specified precision
* xtype = 'R' (radians, default) 'D' (degrees) 'G' (grades)
* sin(x) = x-(x**3/3!)+(x**5/5!)-(x**7/7!)+-...
********************************************************************/
Expose precision type
Use Strict Arg x,xprec=(precision),xtype=(type)
iprec=xprec+10 /* internal precision */
Numeric Digits iprec
/* first use pi constant or compute it if necessary */
pi=self~pi(iprec)
/* normalize x to be between 0 and 2*pi (or equivalent) */
/* and convert degrees or grades to radians */
xx=x
Select
When xtype='R' Then Do
Do While xx>=pi*2; xx=xx-pi*2; End
Do While xx<0; xx=xx+pi*2; End
End
When xtype='D' Then Do
Do While xx>=360; xx=xx-360; End
Do While xx<0; xx=xx+360; End
xx=xx*pi/180
End
When xtype='G' Then Do
Do While xx>=400; xx=xx-400; End
Do While xx<0; xx=xx+400; End
xx=xx*pi/200
End
End
/* normalize xx to be between 0 and pi/2 */
sign=1
Select
When xx<=pi/2 Then Nop
When xx<=pi Then xx=pi-xx
When xx<=3*pi/2 Then Do; sign=-1; xx=xx-pi; End
Otherwise Do; sign=-1; xx=2*pi-xx; End
End
/* now compute the Taylor series for the normalized xx */
o=xx
u=1
r=xx
If abs(xx)<10**(-iprec) Then
r=0
Else Do
Do i=3 By 2 Until ra=r
ra=r
o=-o*xx*xx
u=u*i*(i-1)
r=r+(o/u)
End
End
Numeric Digits xprec
Return sign*(r+0)
::Method sinh
/* REXX ****************************************************************
* Return sinh(x,precision) -- with specified precision
* sinh(x) = x+(x**3/3!)+(x**5/5!)+(x**7/7!)+-...
* 920903 Walter Pachl
***********************************************************************/
Expose precision
Use Strict Arg x,xprec=(precision)
iprec=xprec+10
Numeric Digits iprec
o=x
u=1
r=x
Do i=3 By 2 Until ra=r
ra=r
o=o*x*x
u=u*i*(i-1)
r=r+(o/u)
End
Numeric Digits xprec
Return (r+0)
::Method tan
/* REXX *************************************************************
* Return tan(x,precision,type) -- with the specified precision
* tan(x)=sin(x)/cos(x)
********************************************************************/
Expose precision type
Use Strict Arg x,xprec=(precision),xtype=(type)
iprec=xprec+10
Numeric Digits iprec
s=self~sin(x,iprec,xtype)
c=self~cos(x,iprec,xtype)
If c=0 Then
Return '+infinity'
t=s/c
Numeric Digits xprec
Return (t+0)
::Method tanh
/***********************************************************************
* Return tanh(x,precision) -- with specified precision
* tanh(x) = sinh(x)/cosh(x)
***********************************************************************/
Expose precision
Use Strict Arg x,xprec=(precision)
iprec=xprec+10
Numeric Digits iprec
r=self~sinh(x,iprec)/self~cosh(x,iprec)
Numeric Digits xprec
Return (r+0)
::routine rxmarccos public
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
If x<-1 | 1<x Then
Return 'nan'
return .my.rxm~arccos(x,xprec,xtype)
::routine rxmarcsin public
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
If wordpos(xtype,'R D G')=0 Then Do
-- Say 'Argument 3 must be R, D, or G'
Raise Syntax 88.907 array(3,'R, D, or G',xtype)
End
If x<-1 | 1<x Then
Return 'nan'
return .my.rxm~arcsin(x,xprec,xtype)
::routine rxmarctan public
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
If wordpos(xtype,'R D G')=0 Then Do
-- Say 'Argument 3 must be R, D, or G'
Raise Syntax 88.907 array(3,'R, D, or G',xtype)
End
return .my.rxm~arctan(x,xprec,xtype)
::routine rxmarsinh public
Use Strict Arg x,xprec=(.my.rxm~precision)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
return .my.rxm~arsinh(x,xprec)
::routine rxmcos public
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
If wordpos(xtype,'R D G')=0 Then Do
-- Say 'Argument 3 must be R, D, or G'
Raise Syntax 88.907 array(3,'R, D, or G',xtype)
End
return .my.rxm~cos(x,xprec,xtype)
::routine rxmcosh public
Use Strict Arg x,xprec=(.my.rxm~precision)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
return .my.rxm~cosh(x,xprec)
::routine rxmcotan public
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
If wordpos(xtype,'R D G')=0 Then Do
-- Say 'Argument 3 must be R, D, or G'
Raise Syntax 88.907 array(3,'R, D, or G',xtype)
End
return .my.rxm~cotan(x,xprec)
::routine rxmexp public
Use Strict Arg x,xprec=(.my.rxm~precision),xbase=''
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
If datatype(xbase,'NUM')=0 & xbase<>'' Then Do
-- Say 'Argument 3 must be omitted or a number'
Raise Syntax 88.902 array(3,xbase)
End
Select
When x<0 Then Do
iprec=xprec+10
Numeric Digits iprec
z=.my.rxm~exp(abs(x),iprec,xbase)
Select
When z=0 Then Return '+infinity'
When datatype(z)<>'NUM' Then Return z
Otherwise r=1/z
End
Numeric Digits xprec
return r+0
End
When x=0 Then Do
If xbase=0 Then
Return 'nan'
Else
Return 1
End
Otherwise
return .my.rxm~exp(x,xprec,xbase)
End
::routine rxmlog public
Use Strict Arg x,xprec=(.my.rxm~precision),xbase=''
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
If xbase<>'' &,
datatype(xbase,'NUM')=0 Then Do
-- Say 'Argument 3 must be a number'
Raise Syntax 88.902 array(3,xbase)
End
If x=0 Then
Return '-infinity'
If x<0 Then
Return 'nan'
return .my.rxm~log(x,xprec,xbase)
::routine rxmlog10 public
Use Strict Arg x,xprec=(.my.rxm~precision)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
If x=0 Then
Return '-infinity'
If x<0 Then
Return 'nan'
return .my.rxm~log10(x,xprec)
::routine rxmpi public
Use Strict Arg xprec=(.my.rxm~precision)
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
return .my.rxm~pi(xprec)
::routine rxmpower public
Use Strict Arg b,e,xprec=(.my.rxm~precision)
If datatype(b,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,b)
End
If datatype(e,'NUM')=0 Then Do
-- Say 'Argument 2 must be a number'
Raise Syntax 88.902 array(2,e)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 3 must be a whole number between 1 and 999999'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 3 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(3,1,999999,xprec)
End
If b<0 & datatype(e,'W')=0 Then
Return 'nan'
return .my.rxm~power(b,e,xprec)
::routine rxmsqrt public
Use Strict Arg x,xprec=(.my.rxm~precision)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
Select
When x<0 Then Return 'nan'
When x=0 Then Return 0
Otherwise
return .my.rxm~sqrt(x,xprec)
End
::routine rxmsin public
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
If wordpos(xtype,'R D G')=0 Then Do
-- Say 'Argument 3 must be R, D, or G'
Raise Syntax 88.907 array(3,'R, D, or G',xtype)
End
return .my.rxm~sin(x,xprec,xtype)
::routine rxmsinh public
Use Strict Arg x,xprec=(.my.rxm~precision)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
return .my.rxm~sinh(x,xprec)
::routine rxmtan public
Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
If wordpos(xtype,'R D G')=0 Then Do
-- Say 'Argument 3 must be R, D, or G'
Raise Syntax 88.907 array(3,'R, D, or G',xtype)
End
return .my.rxm~tan(x,xprec,xtype)
::routine rxmtanh public
Use Strict Arg x,xprec=(.my.rxm~precision)
If datatype(x,'NUM')=0 Then Do
-- Say 'Argument 1 must be a number'
Raise Syntax 88.902 array(1,x)
End
If datatype(xprec,'W')=0 Then Do
-- Say 'Argument 2 must be a positive whole number'
Raise Syntax 88.905 array(2,xprec)
End
If xprec<1 | 999999<xprec Then Do
-- Say 'Argument 2 must be a whole number between 1 and 999999'
Raise Syntax 88.907 array(2,1,999999,xprec)
End
return .my.rxm~tanh(x,xprec)
::routine rxmhelp public
Use Arg xprec=(.my.rxm~precision),xtype=(.my.rxm~type)
Say 'precision='xprec
Say ' type='xtype
Parse source s; Say ' source='s
Parse version v; Say ' version='v
Do si=2 To 5
Say substr(sourceline(si),3)
End
Say 'You can change the default precision and type as follows:'
Say " .locaL~my.rxm~precision=50"
Say " .locaL~my.rxm~type='R'"
return 0
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
PARI/GP
Pari accepts only radians; the conversion is simple but not included here.
cos(Pi/2)
sin(Pi/2)
tan(Pi/2)
acos(1)
asin(1)
atan(1)
apply(f->f(1), [cos,sin,tan,acos,asin,atan])
Pascal
Program TrigonometricFuntions(output);
uses
math;
var
radians, degree: double;
begin
radians := pi / 4.0;
degree := 45;
// Pascal works in radians. Necessary degree-radian conversions are shown.
writeln (sin(radians),' ', sin(degree/180*pi));
writeln (cos(radians),' ', cos(degree/180*pi));
writeln (tan(radians),' ', tan(degree/180*pi));
writeln ();
writeln (arcsin(sin(radians)),' Rad., or ', arcsin(sin(degree/180*pi))/pi*180,' Deg.');
writeln (arccos(cos(radians)),' Rad., or ', arccos(cos(degree/180*pi))/pi*180,' Deg.');
writeln (arctan(tan(radians)),' Rad., or ', arctan(tan(degree/180*pi))/pi*180,' Deg.');
// ( radians ) / pi * 180 = deg.
end.
- Output:
7.0710678118654750E-0001 7.0710678118654752E-0001 7.0710678118654755E-0001 7.0710678118654752E-0001 9.9999999999999994E-0001 1.0000000000000000E+0000 7.8539816339744828E-0001 Rad., or 4.5000000000000000E+0001 Deg. 7.8539816339744828E-0001 Rad., or 4.5000000000000000E+0001 Deg. 7.8539816339744828E-0001 Rad., or 4.5000000000000000E+0001 Deg.
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";
- 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
Phix
with javascript_semantics ?sin(PI/2) ?sin(90*PI/180) ?cos(0) ?cos(0*PI/180) ?tan(PI/4) ?tan(45*PI/180) ?arcsin(1)*2 ?arcsin(1)*180/PI ?arccos(0)*2 ?arccos(0)*180/PI ?arctan(1)*4 ?arctan(1)*180/PI
- Output:
1 1 1 1 1.0 1.0 3.141592654 90 3.141592654 90 3.141592654 45
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;
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) )
- 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
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);
Results:
5.00000E-0001 5.00000E-0001 5.00000E-0001 7.07107E-0001 7.07107E-0001 4.50000E+0001 5.21095E-0001 1.12763E+0000 5.00000E-0001
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.
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;
- 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
ATAN2(n1,n2) --Arctangent(y/x), -pi < result <= +pi
SINH(n) --Hyperbolic sine
COSH(n) --Hyperbolic cosine
TANH(n) --Hyperbolic tangent
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.
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) =>
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 =
- Output:
1.0 0.5 1.0 60.0
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)
- 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
A More "PowerShelly" Way
I would send the output as an array of objects containing the ([double]
) properties: Radians and Degrees.
Notice the difference between the last decimal place in the first two objects. If you were calculating coordinates as a civil engineer or land surveyor this difference could affect your measurments. Additionally, the output is an array of objects containing [double]
values rather than an array of strings.
$radians = [Math]::PI / 4
$degrees = 45
[PSCustomObject]@{Radians=[Math]::Sin($radians); Degrees=[Math]::Sin($degrees * [Math]::PI / 180)}
[PSCustomObject]@{Radians=[Math]::Cos($radians); Degrees=[Math]::Cos($degrees * [Math]::PI / 180)}
[PSCustomObject]@{Radians=[Math]::Tan($radians); Degrees=[Math]::Tan($degrees * [Math]::PI / 180)}
[double]$tempVar = [Math]::Asin([Math]::Sin($radians))
[PSCustomObject]@{Radians=$tempVar; Degrees=$tempVar * 180 / [Math]::PI}
[double]$tempVar = [Math]::Acos([Math]::Cos($radians))
[PSCustomObject]@{Radians=$tempVar; Degrees=$tempVar * 180 / [Math]::PI}
[double]$tempVar = [Math]::Atan([Math]::Tan($radians))
[PSCustomObject]@{Radians=$tempVar; Degrees=$tempVar * 180 / [Math]::PI}
- Output:
Radians Degrees ------- ------- 0.707106781186547 0.707106781186547 0.707106781186548 0.707106781186548 1 1 0.785398163397448 45 0.785398163397448 45 0.785398163397448 45
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()
- 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.
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
>>>
Quackery
v**
is defined at Exponentiation operator#Quackery.
Please note, the code presented here is sufficient to the task, but is not a practical implementation for the reasons discussed below. The intent of this entry is to invite discussion on the subject of Padé Approximants, the method used here. To that end I have opened a section on the subject in the Discussion page of this task, and invite you to contribute to it if you have useful knowledge of Padé Approximants.
Full disclosure - I am not a mathematician, I am an amateur programmer who has recently heard of Padé Approximants and is desirous of learning more, as they look to be a useful tool, but not a panacea.
A search of Rosetta Code at the time of writing (14 July 2021) finds no references to Padé or Pade on the site. A more general search of the Internet turns up such phrases as "is the "best" approximation of a function by a rational function of given order" and "The unreasonable effectiveness of Pade approximation", which piqued my interest. Generally there are scholarly papers in the subject that whoosh right over my head, and very little at the "pop-maths" level, i.e. no videos by my go-to YouTube channels - numberphile/computerphile, 3blue1brown, mathologer.
In the absence of sources pitched at my level, this is the methodology I have developed to create this code.
Step 1. Use Wolfram Alpha to find Padé Approximants for a function. Here is the relevant documentation for Mathematica, which also applies to Wolfram Alpha. Link: PadeApproximant.
Here are the inputs to Wolfram Alpha used in generating this Quackery code. sin, cos, tan, arcsin, arccos, and arctan.
Note that the exact result for arccos
includes several instances of the irrational number π, which is not ideal given that the intent is to generate a rational approximation, so instead I used the identity arccos(x)=π/2-arcsin(x), which Wolfram Alpha lists amongst the "Alternate forms", reducing the number of uses of π to one.
Step 2. Use GeoGebra to see the range of arguments over which the Padé approximant is valid, and to identify the range in which it will return values correct to a given number of decimal places. In each of the following examples, function f
is a Padé Approximant, function g
is the function that f
is approximating, and function h
is the difference between f
and g
, multiplied by 10^n
, where n
can be varied with a slider. Where the h
line is very close to zero, the approximation will be good to n
decimal places.
Your attention is drawn to the task output for arccos
, which is only good to a couple of decimal places for the argument passed to it. This is explained by the corresponding graph in Geogebra, where we can see that the argument is outside the safe (i.e. h
is close to zero) range for anything other than very small values of n
.
Geogebra graphs for the functions defined in this task: sin, cos, tan, arcsin, arccos, arctan.
Step 3. Iterate over steps 1 and 2 until you find appropriate Padé Approximants for the task at hand, or conclude that none exist. Assuming the former;
Step 4. Code in a suitable language (i.e. probably not Quackery - efficiency was not a design criterion for Quackery, the language is intended to be the simplest possible introduction to Concatenative/Stack based programming, and is consequently suitable for hobbyist and educational use only) with any obvious optimisations, and use symmetries and identities of the function to extend the range of arguments that can be passed to it. (Not done here - the code serves solely to demonstrate the one-to-one correspondence between a proof-of-concept coding and the formula returned by Wolfram Alpha.)
Note also that the approximation of π/2 is good to 40 decimal places. This is intentional overkill, so that I can be sure that it is not the cause of any inaccuracies. Reducing the size of the numerator and denomination to more sensible values would be part of the optimisation process.
[ $" bigrat.qky' loadfile ] now!
[ 2646693125139304345
1684937174853026414 ] is pi/2 ( --> n/d )
[ 2dup
2dup 3 v** 2363 18183 v* v-
2over 5 v** 12671 4363920 v* v+
2swap 1 1
2over 2 v** 445 12122 v* v+
2over 4 v** 601 872784 v* v+
2swap 6 v** 121 16662240 v* v+
v/ ] is sin ( n/d --> n/d )
[ 1 1
2over 2 v** 3665 7788 v* v-
2over 4 v** 711 25960 v* v+
2over 6 v** 2923 7850304 v* v-
2swap 1 1
2over 2 v** 229 7788 v* v+
2over 4 v** 1 2360 v* v+
2swap 6 v** 127 39251520 v* v+
v/ ] is cos ( n/d --> n/d )
[ 2dup
2dup 3 v** 5 39 v* v-
2over 5 v** 2 715 v* v+
2over 7 v** 1 135135 v* v-
2swap 1 1
2over 2 v** 6 13 v* v-
2over 4 v** 10 429 v* v+
2swap 6 v** 4 19305 v* v-
v/ ] is tan ( n/d --> n/d )
[ 2dup
2dup 3 v** 2318543 2278617 v* v-
2over 5 v** 12022609 60763120 v* v+
2swap 1 1
2over 2 v** 1798875 1519078 v* v-
2over 4 v** 3891575 12152624 v* v+
2swap 6 v** 4695545 510410208 v* v-
v/ ] is arcsin ( n/d --> n/d )
[ pi/2 2swap arcsin v- ] is arccos ( n/d --> n/d )
[ 2dup
2dup 3 v** 50 39 v* v+
2over 5 v** 283 715 v* v+
2over 7 v** 256 15015 v* v+
2swap 1 1
2over 2 v** 21 13 v* v+
2over 4 v** 105 143 v* v+
2swap 6 v** 35 429 v* v+
v/ ] is arctan ( n/d --> n/d )
[ pi/2 v* 90 1 v/ ] is deg->rad ( n/d --> n/d )
[ pi/2 v/ 90 1 v* ] is rad->deg ( n/d --> n/d )
say "With an argument of 0.5 radians"
cr cr
$ "0.5" $->v drop
sin
say "Sin approximation: " 20 point$ echo$ cr
say " Actual value: 0.47942553860420300027..."
cr cr
$ "0.5" $->v drop
cos
say "Cos approximation: " 20 point$ echo$ cr
say " Actual value: 0.87758256189037271611..."
cr cr
$ "0.5" $->v drop
tan
say "Tan approximation: " 20 point$ echo$ cr
say " Actual value: 0.54630248984379051325..."
cr cr cr
say "To radians, using approximated values from previous computations"
cr cr
$ "0.47942553860423933121" $->v drop
arcsin
say "Arcsin approximation: " 20 point$ echo$ cr
say " Actual value: 0.5"
cr cr
$ "0.87758256189037190908" $->v drop
arccos
say "Arccos approximation: " 20 point$ echo$ cr
say " Actual value: 0.5"
cr cr
$ "0.54630248984379037103" $->v drop
arctan
say "Arctan approximation: " 20 point$ echo$ cr
say " Actual value: 0.5"
cr cr cr
say "0.5 radians is approx 28.64788976 degrees" cr
cr
$ "28.64788976" $->v drop
deg->rad sin
say "Sin approximation: " 20 point$ echo$ cr
say " Actual value: 0.47942553865718102604..."
cr cr
$ "28.64788976" $->v drop
deg->rad cos
say "Cos approximation: " 20 point$ echo$ cr
say " Actual value: 0.87758256186143068872..."
cr cr
$ "28.64788976" $->v drop
deg->rad tan
say "Tan approximation: " 20 point$ echo$ cr
say " Actual value: 0.54630248992217530618..."
cr cr cr
say "To degrees, using approximated values from previous computations"
cr cr
$ "0.47942553865721735699" $->v drop
arcsin rad->deg
say "Arcsin approximation: " 20 point$ echo$ cr
say " Actual value: 28.64788976..."
cr cr
$ "0.87758256186142988169" $->v drop
arccos rad->deg
say "Arccos approximation: " 20 point$ echo$ cr
say " Actual value: 28.64788976..."
cr cr
$ "0.54630248992217516396" $->v drop
arctan rad->deg
say "Arctan approximation: " 20 point$ echo$ cr
say " Actual value: 28.64788976..."
- Output:
With an argument of 0.5 radians Sin approximation: 0.47942553860423933121 Actual value: 0.47942553860420300027... Cos approximation: 0.87758256189037190908 Actual value: 0.87758256189037271611... Tan approximation: 0.54630248984379037103 Actual value: 0.54630248984379051325... To radians, using approximated values from previous computations Arcsin approximation: 0.49999997409078633068 Actual value: 0.5 Arccos approximation: 0.50090902435100642663 Actual value: 0.5 Arctan approximation: 0.50000000390223900073 Actual value: 0.5 0.5 radians is approx 28.64788976 degrees Sin approximation: 0.47942553865721735699 Actual value: 0.47942553865718102604... Cos approximation: 0.87758256186142988169 Actual value: 0.87758256186143068872... Tan approximation: 0.54630248992217516396 Actual value: 0.54630248992217530618... To degrees, using approximated values from previous computations Arcsin approximation: 28.64788827551140385372 Actual value: 28.64788976... Arccos approximation: 28.69997301874556855873 Actual value: 28.64788976... Arctan approximation: 28.64788998358182581534 Actual value: 28.64788976... Stack empty.
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) ) )
Racket
#lang racket
(define radians (/ pi 4))
(define degrees 45)
(displayln (format "~a ~a" (sin radians) (sin (* degrees (/ pi 180)))))
(displayln (format "~a ~a" (cos radians) (cos (* degrees (/ pi 180)))))
(displayln (format "~a ~a" (tan radians) (tan (* degrees (/ pi 180)))))
(define arcsin (asin (sin radians)))
(displayln (format "~a ~a" arcsin (* arcsin (/ 180 pi))))
(define arccos (acos (cos radians)))
(displayln (format "~a ~a" arccos (* arccos (/ 180 pi))))
(define arctan (atan (tan radians)))
(display (format "~a ~a" arctan (* arctan (/ 180 pi))))
Raku
(formerly Perl 6) Borrow the degree to radian routine from here.
# 20210212 Updated Raku programming solution
sub postfix:<°> (\ᵒ) { ᵒ × τ / 360 }
sub postfix:<㎭🡆°> (\ᶜ) { ᶜ / π × 180 }
say sin π/3 ;
say sin 60° ;
say cos π/4 ;
say cos 45° ;
say tan π/6 ;
say tan 30° ;
( asin(3.sqrt/2), acos(1/sqrt 2), atan(1/sqrt 3) )».&{ .say and .㎭🡆°.say }
- Output:
0.8660254037844386 0.8660254037844386 0.7071067811865476 0.7071067811865476 0.5773502691896257 0.5773502691896257 1.0471975511965976 60 0.7853981633974484 45.00000000000001 0.5235987755982989 30.000000000000004
RapidQ
$APPTYPE CONSOLE
$TYPECHECK ON
SUB pause(prompt$)
PRINT prompt$
DO
SLEEP .1
LOOP UNTIL LEN(INKEY$) > 0
END SUB
'MAIN
DEFDBL pi , radians , degrees , deg2rad
pi = 4 * ATAN(1)
deg2rad = pi / 180
radians = pi / 4
degrees = 45 * deg2rad
PRINT format$("%.6n" , SIN(radians)) + " " + format$("%.6n" , SIN(degrees))
PRINT format$("%.6n" , COS(radians)) + " " + format$("%.6n" , COS(degrees))
PRINT format$("%.6n" , TAN(radians)) + " " + format$("%.6n" , TAN(degrees))
DEFDBL temp = SIN(radians)
PRINT format$("%.6n" , ASIN(temp)) + " " + format$("%.6n" , ASIN(temp) / deg2rad)
temp = COS(radians)
PRINT format$("%.6n" , ACOS(temp)) + " " + format$("%.6n" , ACOS(temp) / deg2rad)
temp = TAN(radians)
PRINT format$("%.6n" , ATAN(temp)) + " " + format$("%.6n" , ATAN(temp) / deg2rad)
pause("Press any key to continue.")
END 'MAIN
Rapira
output: sin(pi/2), " ", cos(0), " ", tg(pi/4)
REBOL
REBOL [
Title: "Trigonometric Functions"
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]
- 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'll have to roll your own. Some of the normal/regular trigonometric functions are included here.
┌──────────────────────────────────────────────────────────────────────────┐ │ One common method that ensures enough accuracy in REXX is specifying │ │ more precision (via NUMERIC DIGITS nnn) than is needed, and then │ │ displaying the number of digits that are 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. │ └──────────────────────────────────────────────────────────────────────────┘
Most math (POW, EXP, LOG, LN, GAMMA, etc.), trigonometric, 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, they could be extended 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 unwieldy large.
/*REXX program demonstrates some common trig functions (30 decimal digits are shown).*/
showdigs= 25 /*show only 25 digits of number. */
numeric digits showdigs + 10 /*DIGITS default is 9, but use */
/*extra digs to prevent rounding.*/
say 'Using' showdigs 'decimal digits precision.' /*show # decimal digs being used.*/
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 TANGENT 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.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a
if a>1 then call AsinErr x /*X argument is out of range. */
if a >= sqrt(2) * .5 then return sign(x) * acos( sqrt(1 - aa), '-ASIN')
do j=2 by 2 until p=z; p=z; o= o * aa * (j-1) / j; z= z +o / (j+1); end
return z /* [↑] compute until no noise. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Acos: procedure; parse arg x; if x<-1 | x>1 then call AcosErr; return pi()*.5 - Asin(x)
AcosD: return r2d( Acos( arg(1) ) )
AsinD: return r2d( Asin( arg(1) ) )
cosD: return cos( d2r( arg(1) ) )
sinD: return sin( d2r( d2d( arg(1) ) ) )
tan: procedure; parse 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 ──► a unit circle*/
d2r: return r2r( d2d( arg(1) )*pi() / 180) /*convert degrees ──► radians. */
r2d: return d2d( ( arg(1) * 180 / pi() ) ) /*convert radians ──► degrees. */
r2r: return arg(1) // (pi() *2) /*normalize radians ──► a 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
/*──────────────────────────────────────────────────────────────────────────────────────*/
Atan: procedure; parse arg x; if abs(x)=1 then return pi() * .25 * sign(x)
return Asin(x / sqrt(1 + x*x) )
/*──────────────────────────────────────────────────────────────────────────────────────*/
cos: procedure; parse arg x; x= r2r(x); if x=0 then return 1; a= abs(x)
numeric fuzz min(6, digits() - 3); if a=pi then return -1; pih= pi * .5
if a=pih | a=pih*3 then return 0; pit= pi/3; if a=pit then return .5
if a=pit + pit then return -.5; return .sinCos(1, -1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
sin: procedure; arg x;x=r2r(x);if x=0 then return 0;numeric fuzz min(5,max(1,digits()-3))
if x=pi*.5 then return 1; if x==pi * 1.5 then return -1
if abs(x)=pi then return 0; return .sinCos(x,1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
.sinCos: parse arg z 1 _,i; q= x*x
do k=2 by 2 until p=z; p= z; _= - _ * q / (k * (k+i) ); z= z + _; end
return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9; h= d+6
numeric digits; numeric form; if x<0 then do; x= -x; i= 'i'; end
parse value format(x, 2, 1, , 0) 'E0' with g 'E' _ .; g= g *.5'e'_ % 2
do j=0 while h>9; m.j=h; h= h % 2 + 1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g) * .5; end /*k*/
numeric digits d; return (g/1)i /*make complex if X < 0.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
e: e = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535
return e /*Note: the actual E subroutine returns E's accuracy that */
/*matches the current NUMERIC DIGITS, up to 1 million digits.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
exp: procedure; parse 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= e()**ix * z; return z
/*──────────────────────────────────────────────────────────────────────────────────────*/
pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078164062862
return pi /*Note: the actual 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. */
Programming note:
╔═════════════════════════════════════════════════════════════════════════════╗ ║ Functions that are not included here are (among others): ║ ║ ║ ║ some of the usual higher-math functions normally associated with trig ║ ║ functions: POW, GAMMA, LGGAMMA, ERF, ERFC, ROOT, ATAN2, ║ ║ LOG (LN), LOG2, LOG10, and all of the ║ ║ hyperbolic trigonometric functions and their inverses (too many to list ║ ║ here), ║ ║ angle conversions/normalizations: degrees/radians/grads/mils: ║ ║ a circle ≡ 2 pi radians ≡ 360 degrees ≡ 400 grads ≡ 6400 mils. ║ ║ ║ ║ Some of the other trigonometric functions are (hyphens added intentionally):║ ║ ║ ║ 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 ver-cosine) ║ ║ VSN (versed sine or ver-sine) ║ ║ XCS (ex-secant) ║ ║ COS/SIN/TAN cardinal (damped COS/SIN/TAN functions) ║ ║ COS/SIN integral ║ ║ ║ ║ and all pertinent inverses of the above functions (AVSN, ACVS, ···). ║ ╚═════════════════════════════════════════════════════════════════════════════╝
- output:
(Shown at three-quarter size.)
Using 25 decimal digits precision. -180 degrees, rads= -3.1415926535897932384626 sin= 0 cos= -1 tan= 0 -165 degrees, rads= -2.8797932657906438019240 sin= -0.2588190451025207623488 cos= -0.9659258262890682867497 tan= 0.2679491924311227064725 -150 degrees, rads= -2.6179938779914943653855 sin= -0.5 cos= -0.8660254037844386467637 tan= 0.5773502691896257645091 -135 degrees, rads= -2.3561944901923449288469 sin= -0.7071067811865475244008 cos= -0.7071067811865475244008 tan= 1 -120 degrees, rads= -2.0943951023931954923084 sin= -0.8660254037844386467637 cos= -0.5 tan= 1.7320508075688772935274 -105 degrees, rads= -1.8325957145940460557698 sin= -0.9659258262890682867497 cos= -0.2588190451025207623488 tan= 3.7320508075688772935274 -90 degrees, rads= -1.5707963267948966192313 sin= -1 cos= 0 -75 degrees, rads= -1.3089969389957471826927 sin= -0.9659258262890682867497 cos= 0.2588190451025207623488 tan= -3.7320508075688772935274 -60 degrees, rads= -1.0471975511965977461542 sin= -0.8660254037844386467637 cos= 0.5 tan= -1.7320508075688772935274 -45 degrees, rads= -0.7853981633974483096156 sin= -0.7071067811865475244008 cos= 0.7071067811865475244008 tan= -1 -30 degrees, rads= -0.5235987755982988730771 sin= -0.5 cos= 0.8660254037844386467637 tan= -0.5773502691896257645091 -15 degrees, rads= -0.2617993877991494365385 sin= -0.2588190451025207623488 cos= 0.9659258262890682867497 tan= -0.2679491924311227064725 0 degrees, rads= 0 sin= 0 cos= 1 tan= 0 15 degrees, rads= 0.2617993877991494365385 sin= 0.2588190451025207623488 cos= 0.9659258262890682867497 tan= 0.2679491924311227064725 30 degrees, rads= 0.5235987755982988730771 sin= 0.5 cos= 0.8660254037844386467637 tan= 0.5773502691896257645091 45 degrees, rads= 0.7853981633974483096156 sin= 0.7071067811865475244008 cos= 0.7071067811865475244008 tan= 1 60 degrees, rads= 1.0471975511965977461542 sin= 0.8660254037844386467637 cos= 0.5 tan= 1.7320508075688772935274 75 degrees, rads= 1.3089969389957471826927 sin= 0.9659258262890682867497 cos= 0.2588190451025207623488 tan= 3.7320508075688772935274 90 degrees, rads= 1.5707963267948966192313 sin= 1 cos= 0 105 degrees, rads= 1.8325957145940460557698 sin= 0.9659258262890682867497 cos= -0.2588190451025207623488 tan= -3.7320508075688772935274 120 degrees, rads= 2.0943951023931954923084 sin= 0.8660254037844386467637 cos= -0.5 tan= -1.7320508075688772935274 135 degrees, rads= 2.3561944901923449288469 sin= 0.7071067811865475244008 cos= -0.7071067811865475244008 tan= -1 150 degrees, rads= 2.6179938779914943653855 sin= 0.5 cos= -0.8660254037844386467637 tan= -0.5773502691896257645091 165 degrees, rads= 2.8797932657906438019240 sin= 0.2588190451025207623488 cos= -0.9659258262890682867497 tan= -0.2679491924311227064725 180 degrees, rads= 3.1415926535897932384626 sin= 0 cos= -1 tan= 0 -1 radians, degs= -57.295779513082320876798 Acos= 3.1415926535897932384626 Asin= -1.5707963267948966192313 Atan= -0.7853981633974483096156 -0.5 radians, degs= -28.647889756541160438399 Acos= 2.0943951023931954923084 Asin= -0.5235987755982988730771 Atan= -0.4636476090008061162142 0 radians, degs= 0 Acos= 1.5707963267948966192313 Asin= 0 Atan= 0 0.5 radians, degs= 28.647889756541160438399 Acos= 1.0471975511965977461542 Asin= 0.5235987755982988730771 Atan= 0.4636476090008061162142 1.0 radians, degs= 57.295779513082320876798 Acos= 0 Asin= 1.5707963267948966192313 Atan= 0.7853981633974483096156
Ring
pi = 3.14
decimals(8)
see "sin(pi/4.0) = " + sin(pi/4.0) + nl
see "cos(pi/4.0) = " + cos(pi/4.0) + nl
see "tan(pi/4.0) = " + tan(pi/4.0)+ nl
see "asin(sin(pi/4.0)) = " + asin(sin(pi/4.0)) + nl
see "acos(cos(pi/4.0)) = " + acos(cos(pi/4.0)) + nl
see "atan(tan(pi/4.0)) = " + atan(tan(pi/4.0)) + nl
see "atan2(3,4) = " + atan2(3,4) + nl
RPL
RPL has somewhere a system flag that defines if arguments passed to trigonometric functions are in degrees or radians. The words DEG
and RAD
set the flag appropriately.
We can therefore answer the task so:
π 4 / →NUM 'XRAD' STO 45 'XDEG' STO XRAD RAD SIN XDEG DEG SIN
which will return .707106781187
2 times.
Another way is to stay in the same trigonometric mode and use D→R
or R→D
conversion words. This is the way used below:
RAD π 4 / →NUM SIN 45 D→R SIN π 3 / →NUM COS 60 D→R COS π 6 / →NUM TAN 30 D→R TAN
- Output:
6: .707106781187 5: .707106781187 4: .499999999997 3: .499999999997 2: .577350269189 1: .577350269189
As we have now in the stack the 6 values to be inversed, let's call the required functions in reverse order. The 6 ROLLD
instruction pushes the number from level 1 to level 6 of the stack, making thus the next number available for inversion.
ATAN R→D 6 ROLLD ATAN 6 ROLLD ACOS R→D 6 ROLLD ACOS 6 ROLLD ASIN R→D 6 ROLLD ASIN 6 ROLLD
- Output:
6: .785398163397 5: 45 4: 1.0471975512 3: 60.0000000002 2: .523598775598 1: 30
Calculations made with a HP-28S. Emulator has better precision and returns 60 for 60 D→R COS ACOS R→D
Ruby
Ruby's Math module contains all six functions. The functions all accept radians only, so conversion is necessary when dealing with degrees.
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)}"
- 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
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.
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")
- 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
' Find these three ratios: Sine, Cosine, Tangent. (These ratios have NO units.)
deg = 45.0
' Run BASIC works in radians; so, first convert deg to rad as shown in next line.
rad = deg * (atn(1)/45)
print "Ratios for a "; deg; " degree angle, (or "; rad; " radian angle.)"
print "Sine: "; SIN(rad)
print "Cosine: "; COS(rad)
print "Tangent: "; TAN(rad)
print "Inverse Functions - - (Using above ratios)"
' Now, use those ratios to work backwards to show their original angle in radians.
' Also, use this: rad / (atn(1)/45) = deg (To change radians to degrees.)
print "Arcsine: "; ASN(SIN(rad)); " radians, (or "; ASN(SIN(rad))/(atn(1)/45); " degrees)"
print "Arccosine: "; ACS(COS(rad)); " radians, (or "; ACS(COS(rad))/(atn(1)/45); " degrees)"
print "Arctangent: "; ATN(TAN(rad)); " radians, (or "; ATN(TAN(rad))/(atn(1)/45); " degrees)"
' This code also works in Liberty BASIC.
' The above (atn(1)/45) = approx .01745329252
- Output:
Ratios for a 45.0 degree angle, (or 0.785398163 radian angle.) Sine: 0.707106781 Cosine: 0.707106781 Tangent: 1.0 Inverse Functions - - (Using above ratios) Arcsine: 0.785398163 radians, (or 45.0 degrees) Arccosine: 0.785398163 radians, (or 45.0 degrees) Arctangent: 0.785398163 radians, (or 45.0 degrees)
Rust
// 20210221 Rust programming solution
use std::f64::consts::PI;
fn main() {
let angle_radians: f64 = PI/4.0;
let angle_degrees: f64 = 45.0;
println!("{} {}", angle_radians.sin(), angle_degrees.to_radians().sin());
println!("{} {}", angle_radians.cos(), angle_degrees.to_radians().cos());
println!("{} {}", angle_radians.tan(), angle_degrees.to_radians().tan());
let asin = angle_radians.sin().asin();
println!("{} {}", asin, asin.to_degrees());
let acos = angle_radians.cos().acos();
println!("{} {}", acos, acos.to_degrees());
let atan = angle_radians.tan().atan();
println!("{} {}", atan, atan.to_degrees());
}
- Output:
0.7071067811865475 0.7071067811865475 0.7071067811865476 0.7071067811865476 0.9999999999999999 0.9999999999999999 0.7853981633974482 44.99999999999999 0.7853981633974483 45 0.7853981633974483 45
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;
Scala
import scala.math._
object Gonio extends App {
//Pi / 4 rad is 45 degrees. All answers should be the same.
val radians = Pi / 4
val degrees = 45.0
println(s"${sin(radians)} ${sin(toRadians(degrees))}")
//cosine
println(s"${cos(radians)} ${cos(toRadians(degrees))}")
//tangent
println(s"${tan(radians)} ${tan(toRadians(degrees))}")
//arcsine
val bgsin = asin(sin(radians))
println(s"$bgsin ${toDegrees(bgsin)}")
val bgcos = acos(cos(radians))
println(s"$bgcos ${toDegrees(bgcos)}")
//arctangent
val bgtan = atan(tan(radians))
println(s"$bgtan ${toDegrees(bgtan)}")
val bgtan2 = atan2(1, 1)
println(s"$bgtan ${toDegrees(bgtan)}")
}
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)
Seed7
The example below uses the libaray math.s7i, which defines, besides many other functions, sin, cos, tan, asin, acos and atan.
$ 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;
- 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
Sidef
var angle_deg = 45;
var angle_rad = Num.pi/4;
for arr in [
[sin(angle_rad), sin(deg2rad(angle_deg))],
[cos(angle_rad), cos(deg2rad(angle_deg))],
[tan(angle_rad), tan(deg2rad(angle_deg))],
[cot(angle_rad), cot(deg2rad(angle_deg))],
] {
say arr.join(" ");
}
for n in [
asin(sin(angle_rad)),
acos(cos(angle_rad)),
atan(tan(angle_rad)),
acot(cot(angle_rad)),
] {
say [n, rad2deg(n)].join(' ');
}
- 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
SparForte
As a structured script.
#!/usr/local/bin/spar
pragma annotate( summary, "trig" )
@( description, "If your language has a library or built-in " )
@( description, "functions for trigonometry, show examples of: ")
@( description, "sine, cosine, tangent, inverses (of the above) " )
@( description, "using the same angle in radians and degrees." )
@( description, "" )
@( description, "For the non-inverse functions, each radian/" )
@( description, "degree pair should use arguments that evaluate to " )
@( description, "the same angle (that is, it's not necessary to " )
@( description, "use the same angle for all three regular " )
@( description, "functions as long as the two sine calls use the " )
@( description, "same angle). For the inverse functions, use " )
@( description, "the same number and convert its answer to radians " )
@( description, "and degrees." )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Trigonometric_functions" );
pragma license( unrestricted );
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
procedure trig is
degrees_cycle : constant float := 360.0;
radians_cycle : constant float := 2.0 * float( numerics.pi );
angle_degrees : constant float := 45.0;
angle_radians : constant float := float( numerics.pi ) / 4.0;
begin
put( "Sin " )
@( numerics.sin( angle_degrees, degrees_cycle ) )
@( numerics.sin( angle_radians, radians_cycle ) );
new_line;
put( "Cos " )
@( numerics.cos( angle_degrees, degrees_cycle ) )
@( numerics.cos( angle_radians, radians_cycle ) );
new_line;
put( "Tan " )
@( numerics.tan( angle_degrees, degrees_cycle ) )
@( numerics.tan( angle_radians, radians_cycle ) );
new_line;
put( "Cot " )
@( numerics.cot( angle_degrees, degrees_cycle ) )
@( numerics.cot( angle_radians, radians_cycle ) );
new_line;
put( "Arcsin" )
@( numerics.arcsin( numerics.sin( angle_degrees, degrees_cycle ), degrees_cycle ) )
@( numerics.arcsin( numerics.sin( angle_radians, radians_cycle ), radians_cycle ) );
new_line;
put( "Arccos" )
@( numerics.arccos( numerics.cos( angle_degrees, degrees_cycle ), degrees_cycle ) )
@( numerics.arccos( numerics.cos( angle_radians, radians_cycle ), radians_cycle ) );
new_line;
put( "Arctan" )
@( numerics.arctan( numerics.tan( angle_degrees, degrees_cycle ), 1, degrees_cycle ) )
@( numerics.arctan( numerics.tan( angle_radians, radians_cycle ), 1, radians_cycle ) );
new_line;
put( "Arccot" )
@( numerics.arccot( numerics.cot( angle_degrees, degrees_cycle ), 1, degrees_cycle ) )
@( numerics.arccot( numerics.cot( angle_radians, radians_cycle ), 1, radians_cycle ) );
new_line;
command_line.set_exit_status( 0 );
end trig;
- Output:
$ spar trig Sin 7.07106781186547E-01 7.07106781186547E-01 Cos 7.07106781186547E-01 7.07106781186548E-01 Tan 1.00000000000000E+00 9.99999999999998E-01 Cot 1.00000000000000E+00 1.00000000000000E+00 Arcsin 4.50000000000000E+01 7.85398163397448E-01 Arccos 4.50000000000000E+01 7.85398163397448E-01 Arctan 45 7.85398163397448E-01 Arccot 45 7.85398163397449E-01
SQL PL
With SQL only:
--Conversion
values degrees(3.1415926);
values radians(180);
-- This is equal to Pi.
--PI/4 45
values sin(radians(180)/4);
values sin(radians(45));
values cos(radians(180)/4);
values cos(radians(45));
values tan(radians(180)/4);
values tan(radians(45));
values cot(radians(180)/4);
values cot(radians(45));
values asin(sin(radians(180)/4));
values asin(sin(radians(45)));
values atan(tan(radians(180)/4));
values atan(tan(radians(45)));
--PI/3 60
values sin(radians(180)/3);
values sin(radians(60));
values cos(radians(180)/3);
values cos(radians(60));
values tan(radians(180)/3);
values tan(radians(60));
values cot(radians(180)/3);
values cot(radians(60));
values asin(sin(radians(180)/3));
values asin(sin(radians(60)));
values atan(tan(radians(180)/3));
values atan(tan(radians(60)));
Output:
db2 -tx values degrees(3.1415926) +1.79999996929531E+002 values radians(180) +3.14159265358979E+000 values sin(radians(180)/4) +7.07106781186547E-001 values sin(radians(45)) +7.07106781186547E-001 values cos(radians(180)/4) +7.07106781186548E-001 values cos(radians(45)) +7.07106781186548E-001 values tan(radians(180)/4) +1.00000000000000E+000 values tan(radians(45)) +1.00000000000000E+000 values cot(radians(180)/4) +1.00000000000000E+000 values cot(radians(45)) +1.00000000000000E+000 values asin(sin(radians(180)/4)) +7.85398163397448E-001 values asin(sin(radians(45))) +7.85398163397448E-001 values atan(tan(radians(180)/4)) +7.85398163397448E-001 values atan(tan(radians(45))) +7.85398163397448E-001 values sin(radians(180)/3) +8.66025403784439E-001 values sin(radians(60)) +8.66025403784439E-001 values cos(radians(180)/3) +5.00000000000000E-001 values cos(radians(60)) +5.00000000000000E-001 values tan(radians(180)/3) +1.73205080756888E+000 values tan(radians(60)) +1.73205080756888E+000 values cot(radians(180)/3) +5.77350269189626E-001 values cot(radians(60)) +5.77350269189626E-001 values asin(sin(radians(180)/3)) +1.04719755119660E+000 values asin(sin(radians(60))) +1.04719755119660E+000 values atan(tan(radians(180)/3)) +1.04719755119660E+000 values atan(tan(radians(60))) +1.04719755119660E+000
Stata
Stata computes only in radians, but the conversion is easy.
scalar deg=_pi/180
display cos(30*deg)
display sin(30*deg)
display tan(30*deg)
display cos(_pi/6)
display sin(_pi/6)
display tan(_pi/6)
display acos(0.5)
display asin(0.5)
display atan(0.5)
Tcl
The built-in functions only take radian arguments.
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
0.8660254037844386 0.5000000000000001 1.7320508075688767 1.0471975511965976 59.99999999999999 1.0471975511965976 59.99999999999999 1.0471975511965976 59.99999999999999
VBA
Public Sub trig()
Pi = WorksheetFunction.Pi()
Debug.Print Sin(Pi / 2)
Debug.Print Sin(90 * Pi / 180)
Debug.Print Cos(0)
Debug.Print Cos(0 * Pi / 180)
Debug.Print Tan(Pi / 4)
Debug.Print Tan(45 * Pi / 180)
Debug.Print WorksheetFunction.Asin(1) * 2
Debug.Print WorksheetFunction.Asin(1) * 180 / Pi
Debug.Print WorksheetFunction.Acos(0) * 2
Debug.Print WorksheetFunction.Acos(0) * 180 / Pi
Debug.Print Atn(1) * 4
Debug.Print Atn(1) * 180 / Pi
End Sub
- Output:
1 1 1 1 1 1 3,14159265358979 90 3,14159265358979 90 3,14159265358979 45
Visual Basic .NET
Module Module1
Sub Main()
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)
End Sub
End Module
- Output:
=== radians === sin (pi/3) = 0.866025403784439 cos (pi/3) = 0.5 tan (pi/3) = 1.73205080756888 arcsin (1/2) = 0.523598775598299 arccos (1/2) = 1.0471975511966 arctan (1/2) = 0.463647609000806 === degrees === sin (60) = 0.866025403784439 cos (60) = 0.5 tan (60) = 1.73205080756888 arcsin (1/2) = 30 arccos (1/2) = 60 arctan (1/2) = 26.565051177078
Wren
import "./fmt" for Fmt
var d = 30
var r = d * Num.pi / 180
var s = 0.5
var c = 3.sqrt / 2
var t = 1 / 3.sqrt
Fmt.print("sin($9.6f deg) = $f", d, (d*Num.pi/180).sin)
Fmt.print("sin($9.6f rad) = $f", r, r.sin)
Fmt.print("cos($9.6f deg) = $f", d, (d*Num.pi/180).cos)
Fmt.print("cos($9.6f rad) = $f", r, r.cos)
Fmt.print("tan($9.6f deg) = $f", d, (d*Num.pi/180).tan)
Fmt.print("tan($9.6f rad) = $f", r, r.tan)
Fmt.print("asin($f) = $9.6f deg", s, s.asin*180/Num.pi)
Fmt.print("asin($f) = $9.6f rad", s, s.asin)
Fmt.print("acos($f) = $9.6f deg", c, c.acos*180/Num.pi)
Fmt.print("acos($f) = $9.6f rad", c, c.acos)
Fmt.print("atan($f) = $9.6f deg", t, t.atan*180/Num.pi)
Fmt.print("atan($f) = $9.6f rad", t, t.atan)
- 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
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);
]
- 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
zkl
(30.0).toRad().sin() //-->0.5
(60.0).toRad().cos() //-->0.5
(45.0).toRad().tan() //-->1
(0.523599).sin() //-->0.5
etc
(0.5).asin() //-->0.523599
(0.5).acos() //-->1.0472
(1.0).atan() //-->0.785398
(1.0).atan().toDeg() //-->45
etc
ZX Spectrum Basic
The ZX Spectrum ROM only calculates sine and arctangent directly (via Chebyshev polynomials), and uses internal functions of these (and the square root) to generate the other functions. In particular, arcsin x is calculated as arctan ( x / ( sqrt ( 1 - x * x ) ) + 1 ) / 2, which is why some of these functions are legendarily slow.
10 DEF FN d(a)=a*PI/180:REM convert degrees to radians; all ZX Spectrum trig calculations are done in radians
20 DEF FN i(r)=180*r/PI:REM convert radians to degrees for inverse functions
30 LET d=45
40 LET r=PI/4
50 PRINT SIN r,SIN FN d(d)
60 PRINT COS r,COS FN d(d)
70 PRINT TAN r,TAN FN d(d)
80 PRINT
90 LET d=.5
110 PRINT ASN d,FN i(ASN d)
120 PRINT ACS d,FN i(ACS d)
130 PRINT ATN d,FN i(ATN d)
- Output:
0.70710678 0.70710678 0.70710678 0.70710678 1 1 0.52359878 30 1.0471976 60 0.46364761 26.565051 0 OK, 130:1
- Programming Tasks
- Arithmetic operations
- Mathematics
- 11l
- ACL2
- ACL2 examples needing attention
- Examples needing attention
- ActionScript
- Ada
- ALGOL 68
- ALGOL W
- Arturo
- Asymptote
- AutoHotkey
- Autolisp
- AWK
- Axe
- BaCon
- BASIC
- Applesoft BASIC
- BASIC256
- BBC BASIC
- IS-BASIC
- Yabasic
- Bc
- Bc -l
- BQN
- C
- C sharp
- C++
- Clojure
- COBOL
- Common Lisp
- D
- Delphi
- SysUtils,StdCtrls
- E
- EasyLang
- Elena
- Elixir
- Erlang
- F Sharp
- Factor
- Fantom
- Forth
- Fortran
- FreeBASIC
- FutureBasic
- GAP
- Go
- Groovy
- Haskell
- HicEst
- IDL
- Icon
- Unicon
- J
- Java
- JavaScript
- Jq
- Jsish
- Julia
- Kotlin
- Lambdatalk
- Liberty BASIC
- Logo
- Logtalk
- Lua
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Maxima
- MAXScript
- Metafont
- MiniScript
- МК-61/52
- Modula-2
- NetRexx
- Nim
- OCaml
- Octave
- Oforth
- OoRexx
- Oz
- PARI/GP
- Pascal
- Math
- Perl
- Phix
- Phix/basics
- PHP
- PicoLisp
- PL/I
- PL/SQL
- Pop11
- PostScript
- PowerShell
- PureBasic
- Python
- Quackery
- R
- Racket
- Raku
- RapidQ
- Rapira
- REBOL
- REXX
- Ring
- RPL
- Ruby
- Run BASIC
- Rust
- SAS
- Scala
- Scheme
- Seed7
- Sidef
- SparForte
- SQL PL
- Stata
- Tcl
- VBA
- Visual Basic .NET
- Wren
- Wren-fmt
- XPL0
- Zkl
- ZX Spectrum Basic
- Batch File/Omit
- M4/Omit
- Geometry