Jump to content

Angles (geometric), normalization and conversion: Difference between revisions

m
syntax highlighting fixup automation
(Added XPL0 example.)
m (syntax highlighting fixup automation)
Line 122:
{{trans|Nim}}
 
<langsyntaxhighlight lang=11l>V values = [Float(-2), -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]
 
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)))</langsyntaxhighlight>
 
{{out}}
Line 232:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=AutoHotkey>testAngles := [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]
 
result .= "Degrees Degrees Gradians Mils Radians`n"
Line 301:
return Rad2Rad(Rad) * 3200 / (π:=3.141592653589793)
}
;-------------------------------------------------------</langsyntaxhighlight>
{{out}}
<pre>Degrees Degrees Gradians Mils Radians
Line 360:
 
=={{header|AWK}}==
<langsyntaxhighlight lang=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>
</lang>
{{out}}
<pre>
Line 491:
 
=={{header|C}}==
<langsyntaxhighlight lang=c>#define PI 3.141592653589793
#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;}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang=csharp>using System;
 
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;
}</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 646:
=={{header|C++}}==
{{libheader|Boost}}
<langsyntaxhighlight lang=cpp>#include <functional>
#include <iostream>
#include <iomanip>
Line 713:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> ┌───────────────────┐
Line 753:
or (angles) for auto-test.
VAL* is unnormalized.
<langsyntaxhighlight lang=lisp>(defun DegToDeg (a) (rem a 360))
(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))))</langsyntaxhighlight>
{{out}}
<pre>[CLISP]> (angles)
Line 859:
{{libheader| System.Math}}
{{Trans|Go}}
<langsyntaxhighlight lang=Delphi>
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.</langsyntaxhighlight>
 
=={{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.)
<langsyntaxhighlight lang=factor>USING: accessors combinators formatting inverse kernel math
math.constants quotations qw sequences units.si ;
IN: rosetta-code.angles
Line 1,014:
units [ .row ] cartesian-each ;
 
MAIN: angles</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang=freebasic>#define PI 3.1415926535897932384626433832795028842
#define INVALID -99999
 
Line 1,191:
next i
next k
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,257:
 
=={{header|Go}}==
<langsyntaxhighlight lang=go>package main
 
import (
Line 1,331:
fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a)))
}
}</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight lang=groovy>import java.lang.reflect.Constructor
 
abstract class Angle implements Comparable<? extends Angle> {
Line 1,463:
String unitName() { UNIT }
Radians(Number value = 0) { super(value) }
}</langsyntaxhighlight>
 
This category class allows Angles to interoperate more easily with Numbers:
<langsyntaxhighlight lang=groovy>class AngleCategory {
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) }
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang=groovy>Number.metaClass.mixin AngleCategory
 
[ -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</langsyntaxhighlight>
 
{{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).
 
<langsyntaxhighlight lang=haskell>{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
Line 1,604:
 
to :: forall b a. (Angle a, Angle b) => a -> b
to = fromTurn . toTurn</langsyntaxhighlight>
 
'''Instances of different angular units.'''
 
<langsyntaxhighlight lang=haskell>-- radians
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</langsyntaxhighlight>
 
'''Examples'''
Line 1,716:
The task assignment shows different possible type annotations.
 
<langsyntaxhighlight lang=haskell>main = do
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</langsyntaxhighlight>
 
<pre>λ> main
Line 1,801:
Mil =: adverb def 'normalize as_mil inv m'
Radian =: adverb def 'normalize as_radian inv m'
</syntaxhighlight>
</lang>
we can compose conversion sentences like
<lang>
as_degree 100 Gradian
90
</syntaxhighlight>
</lang>
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>
</lang>
 
=={{header|Java}}==
<langsyntaxhighlight lang=java>import java.text.DecimalFormat;
 
// Title: Angles (geometric), normalization and conversion
Line 1,964:
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,019:
</pre>
=={{header|Javascript}}==
<langsyntaxhighlight lang=javaScript>
/*****************************************************************\
| Expects an angle, an origin unit and a unit to convert to, |
Line 2,081:
}
}
</syntaxhighlight>
</lang>
Output (without bolds and subs):
{{out}}<pre>
Line 2,235:
 
'''Preliminaries'''
<langsyntaxhighlight lang=jq>### Formatting
 
# Right-justify but do not truncate
Line 2,273:
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
</syntaxhighlight>
</lang>
'''The Task'''
<langsyntaxhighlight lang=jq># Normalization as per the task requirements
def mod($y):
(if . < 0 then -$y else 0 end) as $adjust
Line 2,330:
task2, "",
task3, "",
task4</langsyntaxhighlight>
{{out}}
<pre>
Line 2,338:
 
=={{header|Julia}}==
<langsyntaxhighlight lang=julia>using Formatting
 
d2d(d) = d % 360
Line 2,377:
 
testconversions([-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000])
</langsyntaxhighlight>{{out}}
<pre>
Number Units Degrees Gradians Mils Radians
Line 2,432:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang=scala>import java.text.DecimalFormat as DF
 
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)))
}
}</langsyntaxhighlight>
{{out}}
See Java output
 
=={{header|Lua}}==
<langsyntaxhighlight lang=lua>range = { degrees=360, gradians=400, mils=6400, radians=2.0*math.pi }
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</langsyntaxhighlight>
Optionally:
<langsyntaxhighlight lang=lua>-- if you care..
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</langsyntaxhighlight>
{{out}}
<pre> VALUE UNIT = DEGREES GRADIANS MILS RADIANS
Line 2,586:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>ClearAll[NormalizeAngle, NormalizeDegree, NormalizeGradian, NormalizeMil, NormalizeRadian]
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}}]</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight lang=Nim>import math
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}"</langsyntaxhighlight>
 
{{out}}
Line 2,737:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang=perl>use strict;
use warnings;
use feature 'say';
Line 2,770:
printf '%10g %-8s' . '%12g'x4 . "\n", $angle, ${$from}{name}, @results;
}
}</langsyntaxhighlight>
{{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
<!--<langsyntaxhighlight lang=Phix>-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,923:
=={{header|Python}}==
===Python: Original===
<langsyntaxhighlight lang=python>PI = 3.141592653589793
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</langsyntaxhighlight>
 
===Python: using tkinter===
<langsyntaxhighlight lang=python>
''' 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>
</lang>
 
=={{header|Racket}}==
Line 3,321:
{{trans|Common Lisp}}
 
<langsyntaxhighlight lang=racket>#lang racket
 
(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")))</langsyntaxhighlight>
 
{{out}}
Line 3,446:
=={{header|Raku}}==
(formerly Perl 6)
<langsyntaxhighlight lang=perl6>
my @units =
{ code => 'd', name => 'degrees' , number => 360 },
Line 3,475:
@results .fmt('%11g');
}
}</langsyntaxhighlight>
{{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.)''
 
<langsyntaxhighlight lang=perl6>sub postfix:<t>( $t ) { my $a = $t % 1 * τ; $t >=0 ?? $a !! $a - τ }
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);
}
}</langsyntaxhighlight>
 
<pre> Quantity Unit turns degrees gradians mils radians
Line 3,651:
 
=={{header|REXX}}==
<langsyntaxhighlight lang=rexx>/*REXX pgm normalizes an angle (in a scale), or converts angles from a scale to another.*/
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.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; 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.
<langsyntaxhighlight lang=ruby>module Angles
BASES = {"d" => 360, "g" => 400, "m" => 6400, "r" => Math::PI*2 ,"h" => 24 }
Line 3,793:
puts
end
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:45ex"> d g m r h
Line 3,864:
 
=={{header|Rust}}==
<langsyntaxhighlight lang=rust>use std::{
marker::PhantomData,
f64::consts::PI,
Line 3,939:
print_angles::<Mils>();
print_angles::<Radians>();
}</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 4,000:
=={{header|Swift}}==
 
<langsyntaxhighlight lang=swift>import Foundation
 
func normalize(_ f: Double, N: Double) -> Double {
Line 4,077:
 
print()
}</langsyntaxhighlight>
 
{{out}}
Line 4,139:
=={{header|Vlang}}==
{{trans|Go}}
<langsyntaxhighlight lang=vlang>import math
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))}')
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,199:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang=ecmascript>import "/fmt" for 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))
}</langsyntaxhighlight>
 
{{out}}
Line 4,299:
 
=={{header|XPL0}}==
<langsyntaxhighlight lang=XPL0>def Pi = 3.14159265358979323846, N=12, Tab=9;
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);
];
]</langsyntaxhighlight>
 
{{out}}
Line 4,421:
=={{header|zkl}}==
{{trans|Raku}}
<langsyntaxhighlight lang=zkl>var [const]
tau=(0.0).pi*2,
units=Dictionary( // code:(name, units in circle)
Line 4,435:
})
})
;</langsyntaxhighlight>
<langsyntaxhighlight lang=zkl>codes:=units.keys;
println(" Angle Unit ",
codes.apply(fcn(k){ units[k][0] }).apply("%11s".fmt).concat(" "));
Line 4,447:
r.apply("%12g".fmt).concat(" ")));
}
}</langsyntaxhighlight>
{{out}}
<pre style="height:45ex">
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.