Angles (geometric), normalization and conversion: Difference between revisions
Angles (geometric), normalization and conversion (view source)
Revision as of 00:53, 26 August 2022
, 1 year agosyntax highlighting fixup automation
(Added XPL0 example.) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 122:
{{trans|Nim}}
<
F normd(x) {R fmod(x, 360)}
Line 166:
print(‘───────────────────────────────────────────────────────────────────────────────────’)
L(val) values
print(‘#7.7 #7.7 #7.7 #7.7 #7.7’.format(val, normr(val), r2d(val), r2g(val), r2m(val)))</
{{out}}
Line 232:
=={{header|AutoHotkey}}==
<
result .= "Degrees Degrees Gradians Mils Radians`n"
Line 301:
return Rad2Rad(Rad) * 3200 / (π:=3.141592653589793)
}
;-------------------------------------------------------</
{{out}}
<pre>Degrees Degrees Gradians Mils Radians
Line 360:
=={{header|AWK}}==
<
# syntax: GAWK -f ANGLES_(GEOMETRIC)_NORMALIZATION_AND_CONVERSION.AWK
# gawk starts showing discrepancies at test case number 7 when compared with C#
Line 424:
function radian2gradian(angle) { return(angle * 200 / pi) }
function radian2mil(angle) { return(angle * 3200 / pi) }
</syntaxhighlight>
{{out}}
<pre>
Line 491:
=={{header|C}}==
<
#define TWO_PI 6.283185307179586
Line 529:
double rad2deg(double a) {return a * 180 / PI;}
double rad2grad(double a) {return a * 200 / PI;}
double rad2mil(double a) {return a * 3200 / PI;}</
=={{header|C sharp|C#}}==
<
public static class Angles
Line 595:
public static double RadToGrad(double angle) => angle * 200 / Math.PI;
public static double RadToMil(double angle) => angle * 3200 / Math.PI;
}</
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 646:
=={{header|C++}}==
{{libheader|Boost}}
<
#include <iostream>
#include <iomanip>
Line 713:
return 0;
}</
{{out}}
<pre> ┌───────────────────┐
Line 753:
or (angles) for auto-test.
VAL* is unnormalized.
<
(defun GradToGrad (a) (rem a 400))
(defun MilToMil (a) (rem a 6400))
Line 781:
(format t "Grad | ~15f | ~15f | ~15f | ~15f | ~15f~%" a (GradToDeg a) (GradToGrad a) (GradToMil a) (GradToRad a))
(format t "Mil | ~15f | ~15f | ~15f | ~15f | ~15f~%" a (MilToDeg a) (MilToGrad a) (MilToMil a) (MilToRad a))
(format t "Rad | ~15f | ~15f | ~15f | ~15f | ~15f~%~%" a (RadToDeg a) (RadToGrad a) (RadToMil a) (RadToRad a))))</
{{out}}
<pre>[CLISP]> (angles)
Line 859:
{{libheader| System.Math}}
{{Trans|Go}}
<
program normalization_and_conversion;
Line 986:
writeln(format(ft, [s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a))]));
readln;
end.</
=={{header|Factor}}==
Radians and degrees are already defined in the <code>units.si</code> vocabulary. Gradiens and mils are defined in terms of degrees. Conversions from unit to unit are handled by inverse functions; <code>[undo]</code> knows how to deconstruct units in terms of other units. (Assuming, of course, new units are defined entirely with words that have inverses.)
<
math.constants quotations qw sequences units.si ;
IN: rosetta-code.angles
Line 1,014:
units [ .row ] cartesian-each ;
MAIN: angles</
{{out}}
<pre>
Line 1,070:
=={{header|FreeBASIC}}==
Provides a single function that does the normalising and converting. Supports D, G, M, R, T for degrees, gradians, mils, radians, and turns respectively.
<
#define INVALID -99999
Line 1,191:
next i
next k
</syntaxhighlight>
{{out}}
<pre>
Line 1,257:
=={{header|Go}}==
<
import (
Line 1,331:
fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))
}
}</
{{out}}
Line 1,394:
=={{header|Groovy}}==
This solution creates the concept of an angular quantity with subclasses for different units of measure. Rather than creating individual functions (d2d, r2m, etc.) this solution uses inheritance, polymorphism, and operator overloading to implement the conversions and comparisons in a relatively natural way for idiomatic Groovy.
<
abstract class Angle implements Comparable<? extends Angle> {
Line 1,463:
String unitName() { UNIT }
Radians(Number value = 0) { super(value) }
}</
This category class allows Angles to interoperate more easily with Numbers:
<
static Degrees getDeg(Number n) { new Degrees(n) }
static Gradians getGrad(Number n) { new Gradians(n) }
static Mils getMil(Number n) { new Mils(n) }
static Radians getRad(Number n) { new Radians(n) }
}</
Test:
<
[ -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 ].each { rawAngle ->
Line 1,490:
assert 360.deg == 0.deg
assert 90.deg == 100.grad
assert Math.PI.rad == 3200.mil</
{{out}}
Line 1,570:
Isomorphims between all angular types are defined via representation as turns, according to the fact that they all form the same topological space, isomorphic to open interval (-1, 1).
<
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
Line 1,604:
to :: forall b a. (Angle a, Angle b) => a -> b
to = fromTurn . toTurn</
'''Instances of different angular units.'''
<
newtype Rad = Rad Double
deriving (Eq, Ord, Num, Real, Fractional, RealFrac, Floating)
Line 1,675:
toTurn = toTurn @Rad . angle . atan . value
fromTurn = angle . tan . value . fromTurn @Rad
normalize = id</
'''Examples'''
Line 1,716:
The task assignment shows different possible type annotations.
<
let xs = [-2, -1, 0, 1, 2, 6.2831853,
16, 57.2957795, 359, 399, 6399, 1000000]
Line 1,750:
print $ (from :: Grad -> Mil) . angle <$> xs
print $ (from :: Mil -> Mil) . angle <$> xs
print $ (from :: Slope -> Mil) . angle <$> xs</
<pre>λ> main
Line 1,801:
Mil =: adverb def 'normalize as_mil inv m'
Radian =: adverb def 'normalize as_radian inv m'
</syntaxhighlight>
we can compose conversion sentences like
<lang>
as_degree 100 Gradian
90
</syntaxhighlight>
Presuming the following additional definitions:
<lang>
Line 1,860:
|radian | _2 _1 0 1 2 6.28319 3.43363 0.747112 0.858437 3.15933 2.71736 5.92562|
+-------+---------------------------------------------------------------------------------------------------+
</syntaxhighlight>
=={{header|Java}}==
<
// Title: Angles (geometric), normalization and conversion
Line 1,964:
}
}</
{{out}}
Line 2,019:
</pre>
=={{header|Javascript}}==
<
/*****************************************************************\
| Expects an angle, an origin unit and a unit to convert to, |
Line 2,081:
}
}
</syntaxhighlight>
Output (without bolds and subs):
{{out}}<pre>
Line 2,235:
'''Preliminaries'''
<
# Right-justify but do not truncate
Line 2,273:
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
</syntaxhighlight>
'''The Task'''
<
def mod($y):
(if . < 0 then -$y else 0 end) as $adjust
Line 2,330:
task2, "",
task3, "",
task4</
{{out}}
<pre>
Line 2,338:
=={{header|Julia}}==
<
d2d(d) = d % 360
Line 2,377:
testconversions([-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000])
</
<pre>
Number Units Degrees Gradians Mils Radians
Line 2,432:
=={{header|Kotlin}}==
{{trans|Java}}
<
const val DEGREE = 360.0
Line 2,484:
println("%15s %8s = %10s %10s %10s %10s".format(fa.format(a), units, fc.format(d), fc.format(g), fc.format(m), fc.format(r)))
}
}</
{{out}}
See Java output
=={{header|Lua}}==
<
function convert(value, fromunit, tounit)
return math.fmod(value * range[tounit] / range[fromunit], range[tounit])
Line 2,505:
print(string.format("%15.7f %8s = %15.7f %15.7f %15.7f %15.7f", value, fromunit, d, g, m, r))
end
end</
Optionally:
<
assert(convert(-360,"degrees","degrees") == 0.0)
assert(convert(360,"degrees","degrees") == 0.0)
Line 2,533:
function r2g(n) return convert(n,"radians","gradians") end
function r2m(n) return convert(n,"radians","mils") end
function r2r(n) return convert(n,"radians","radians") end</
{{out}}
<pre> VALUE UNIT = DEGREES GRADIANS MILS RADIANS
Line 2,586:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
NormalizeAngle[d_, full_] := Module[{a = d},
If[Abs[a/full] > 4,
Line 2,616:
Mil2Gradian, Mil2Radian, Radian2Degree, Radian2Gradian,
Radian2Mil}, {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399,
6399, 1000000}}]</
{{out}}
<pre>{-(20/9),-(160/9),0,9/10,32,0.098696,9/10,3.58099,(359 \[Pi])/3200,71820/\[Pi],1279800/\[Pi],3200000000/\[Pi]}</pre>
=={{header|Nim}}==
<
import strformat
Line 2,672:
echo "———————————————————————————————————————————————————————————————————————————————————"
for val in Values:
echo fmt"{val:15.7f} {r2r(val):15.7f} {r2d(val):15.7f} {r2g(val):15.7f} {r2m(val):15.7f}"</
{{out}}
Line 2,737:
=={{header|Perl}}==
{{trans|Raku}}
<
use warnings;
use feature 'say';
Line 2,770:
printf '%10g %-8s' . '%12g'x4 . "\n", $angle, ${$from}{name}, @results;
}
}</
{{out}}
<pre> Angle Unit Degrees Gradians Mills Radians
Line 2,836:
=={{header|Phix}}==
Obviously if preferred you could define a long list of routines such as function d2g(atom a) return remainder(a/360,1)*400 end function
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">units</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"degrees"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"gradians"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"mils"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"radians"</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">turns</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">360</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">400</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">6400</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">/</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">}</span>
Line 2,856:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 2,923:
=={{header|Python}}==
===Python: Original===
<
TWO_PI = 6.283185307179586
Line 2,957:
def rad2deg(a): return a * 180.0 / PI
def rad2grad(a): return a * 200.0 / PI
def rad2mil(a): return a * 3200.0 / PI</
===Python: using tkinter===
<
''' Python 3.6.5 code using Tkinter graphical user interface.
Angles (geometric), normalization and conversion challenge.
Line 3,315:
## results matched those from a few other languages on this
## page.
</syntaxhighlight>
=={{header|Racket}}==
Line 3,321:
{{trans|Common Lisp}}
<
(define (rem n m)
Line 3,369:
(displayln
(string-join (map report-angle '(-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000))
"\n\n")))</
{{out}}
Line 3,446:
=={{header|Raku}}==
(formerly Perl 6)
<
my @units =
{ code => 'd', name => 'degrees' , number => 360 },
Line 3,475:
@results .fmt('%11g');
}
}</
{{out}}
<pre> Angle Unit Degrees Gradians Mills Radians
Line 3,543:
''(Much of the complexity is due to the requirement that negative angles must normalize to a negative number.)''
<
sub postfix:<d>( $d ) { my $a = $d % 360 * τ / 360; $d >=0 ?? $a !! $a - τ }
sub postfix:<g>( $g ) { my $a = $g % 400 * τ / 400; $g >=0 ?? $a !! $a - τ }
Line 3,564:
|($a.&f->t, $a.&f->d, $a.&f->g, $a.&f->m, $a.&f->r)».round(.00000001);
}
}</
<pre> Quantity Unit turns degrees gradians mils radians
Line 3,651:
=={{header|REXX}}==
<
numeric digits length( pi() ) - length(.) /*use the "length" of pi for precision.*/
parse arg x /*obtain optional arguments from the CL*/
Line 3,703:
say center(#o,23 ) center(@n #o,w7) center(#a,w7 ) center(#b,w7 ) center(#c,w7 )
say center('',23,_) center('',w7, _) center('',w7,_) center('',w7,_) center('',w7,_)
return /* '↑' seperator line.*/</
{{out|output|text= when using the default input:}}
<pre>
Line 3,769:
=={{header|Ruby}}==
This Angles module responds to methods like r2d. Adding an element (like "h"=>24, for a clock-like angle system) to the BASES hash adds 9 more methods, totaling to 25 methods. None of these methods are actually implemented.
<
BASES = {"d" => 360, "g" => 400, "m" => 6400, "r" => Math::PI*2 ,"h" => 24 }
Line 3,793:
puts
end
</syntaxhighlight>
{{out}}
<pre style="height:45ex"> d g m r h
Line 3,864:
=={{header|Rust}}==
<
marker::PhantomData,
f64::consts::PI,
Line 3,939:
print_angles::<Mils>();
print_angles::<Radians>();
}</
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 4,000:
=={{header|Swift}}==
<
func normalize(_ f: Double, N: Double) -> Double {
Line 4,077:
print()
}</
{{out}}
Line 4,139:
=={{header|Vlang}}==
{{trans|Go}}
<
import strconv
fn d2d(d f64) f64 { return math.mod(d, 360) }
Line 4,191:
println('${s(a)} ${s(r2r(a))} ${s(r2d(a))} ${s(r2g(a))} ${s(r2m(a))}')
}
}</
{{out}}
Line 4,199:
{{trans|Go}}
{{libheader|Wren-fmt}}
<
var d2d = Fn.new { |d| d % 360 }
Line 4,237:
for (a in angles) {
Fmt.print(f2, a, r2r.call(a), r2d.call(a), r2g.call(a), r2m.call(a))
}</
{{out}}
Line 4,299:
=={{header|XPL0}}==
<
func real D2D; real D; return Mod(D, 360.);
func real G2G; real G; return Mod(G, 400.);
Line 4,361:
RlOut(0, R2M(Angle(I))); CrLf(0);
];
]</
{{out}}
Line 4,421:
=={{header|zkl}}==
{{trans|Raku}}
<
tau=(0.0).pi*2,
units=Dictionary( // code:(name, units in circle)
Line 4,435:
})
})
;</
<
println(" Angle Unit ",
codes.apply(fcn(k){ units[k][0] }).apply("%11s".fmt).concat(" "));
Line 4,447:
r.apply("%12g".fmt).concat(" ")));
}
}</
{{out}}
<pre style="height:45ex">
|