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

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 122: Line 122:
{{trans|Nim}}
{{trans|Nim}}


<syntaxhighlight lang=11l>V values = [Float(-2), -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]
<syntaxhighlight 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)}
F normd(x) {R fmod(x, 360)}
Line 232: Line 232:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<syntaxhighlight lang=AutoHotkey>testAngles := [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]
<syntaxhighlight lang="autohotkey">testAngles := [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]


result .= "Degrees Degrees Gradians Mils Radians`n"
result .= "Degrees Degrees Gradians Mils Radians`n"
Line 360: Line 360:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang=AWK>
<syntaxhighlight lang="awk">
# syntax: GAWK -f ANGLES_(GEOMETRIC)_NORMALIZATION_AND_CONVERSION.AWK
# syntax: GAWK -f ANGLES_(GEOMETRIC)_NORMALIZATION_AND_CONVERSION.AWK
# gawk starts showing discrepancies at test case number 7 when compared with C#
# gawk starts showing discrepancies at test case number 7 when compared with C#
Line 491: Line 491:


=={{header|C}}==
=={{header|C}}==
<syntaxhighlight lang=c>#define PI 3.141592653589793
<syntaxhighlight lang="c">#define PI 3.141592653589793
#define TWO_PI 6.283185307179586
#define TWO_PI 6.283185307179586


Line 532: Line 532:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<syntaxhighlight lang=csharp>using System;
<syntaxhighlight lang="csharp">using System;


public static class Angles
public static class Angles
Line 646: Line 646:
=={{header|C++}}==
=={{header|C++}}==
{{libheader|Boost}}
{{libheader|Boost}}
<syntaxhighlight lang=cpp>#include <functional>
<syntaxhighlight lang="cpp">#include <functional>
#include <iostream>
#include <iostream>
#include <iomanip>
#include <iomanip>
Line 753: Line 753:
or (angles) for auto-test.
or (angles) for auto-test.
VAL* is unnormalized.
VAL* is unnormalized.
<syntaxhighlight lang=lisp>(defun DegToDeg (a) (rem a 360))
<syntaxhighlight lang="lisp">(defun DegToDeg (a) (rem a 360))
(defun GradToGrad (a) (rem a 400))
(defun GradToGrad (a) (rem a 400))
(defun MilToMil (a) (rem a 6400))
(defun MilToMil (a) (rem a 6400))
Line 859: Line 859:
{{libheader| System.Math}}
{{libheader| System.Math}}
{{Trans|Go}}
{{Trans|Go}}
<syntaxhighlight lang=Delphi>
<syntaxhighlight lang="delphi">
program normalization_and_conversion;
program normalization_and_conversion;


Line 990: Line 990:
=={{header|Factor}}==
=={{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.)
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.)
<syntaxhighlight lang=factor>USING: accessors combinators formatting inverse kernel math
<syntaxhighlight lang="factor">USING: accessors combinators formatting inverse kernel math
math.constants quotations qw sequences units.si ;
math.constants quotations qw sequences units.si ;
IN: rosetta-code.angles
IN: rosetta-code.angles
Line 1,070: Line 1,070:
=={{header|FreeBASIC}}==
=={{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.
Provides a single function that does the normalising and converting. Supports D, G, M, R, T for degrees, gradians, mils, radians, and turns respectively.
<syntaxhighlight lang=freebasic>#define PI 3.1415926535897932384626433832795028842
<syntaxhighlight lang="freebasic">#define PI 3.1415926535897932384626433832795028842
#define INVALID -99999
#define INVALID -99999


Line 1,257: Line 1,257:


=={{header|Go}}==
=={{header|Go}}==
<syntaxhighlight lang=go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,394: Line 1,394:
=={{header|Groovy}}==
=={{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.
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.
<syntaxhighlight lang=groovy>import java.lang.reflect.Constructor
<syntaxhighlight lang="groovy">import java.lang.reflect.Constructor


abstract class Angle implements Comparable<? extends Angle> {
abstract class Angle implements Comparable<? extends Angle> {
Line 1,466: Line 1,466:


This category class allows Angles to interoperate more easily with Numbers:
This category class allows Angles to interoperate more easily with Numbers:
<syntaxhighlight lang=groovy>class AngleCategory {
<syntaxhighlight lang="groovy">class AngleCategory {
static Degrees getDeg(Number n) { new Degrees(n) }
static Degrees getDeg(Number n) { new Degrees(n) }
static Gradians getGrad(Number n) { new Gradians(n) }
static Gradians getGrad(Number n) { new Gradians(n) }
Line 1,474: Line 1,474:


Test:
Test:
<syntaxhighlight lang=groovy>Number.metaClass.mixin AngleCategory
<syntaxhighlight lang="groovy">Number.metaClass.mixin AngleCategory


[ -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 ].each { rawAngle ->
[ -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 ].each { rawAngle ->
Line 1,570: 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).
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).


<syntaxhighlight lang=haskell>{-# LANGUAGE RankNTypes #-}
<syntaxhighlight lang="haskell">{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
Line 1,608: Line 1,608:
'''Instances of different angular units.'''
'''Instances of different angular units.'''


<syntaxhighlight lang=haskell>-- radians
<syntaxhighlight lang="haskell">-- radians
newtype Rad = Rad Double
newtype Rad = Rad Double
deriving (Eq, Ord, Num, Real, Fractional, RealFrac, Floating)
deriving (Eq, Ord, Num, Real, Fractional, RealFrac, Floating)
Line 1,716: Line 1,716:
The task assignment shows different possible type annotations.
The task assignment shows different possible type annotations.


<syntaxhighlight lang=haskell>main = do
<syntaxhighlight lang="haskell">main = do
let xs = [-2, -1, 0, 1, 2, 6.2831853,
let xs = [-2, -1, 0, 1, 2, 6.2831853,
16, 57.2957795, 359, 399, 6399, 1000000]
16, 57.2957795, 359, 399, 6399, 1000000]
Line 1,783: Line 1,783:
=={{header|J}}==
=={{header|J}}==
given definitions which convert to and from the unit circle, using verbial power (^:) inverse (^: _1), and adverbs to make the sentences read better? or at least differently from other computer languages:
given definitions which convert to and from the unit circle, using verbial power (^:) inverse (^: _1), and adverbs to make the sentences read better? or at least differently from other computer languages:
<lang>
<syntaxhighlight lang="text">
TAU =: 2p1 NB. tauday.com
TAU =: 2p1 NB. tauday.com


Line 1,803: Line 1,803:
</syntaxhighlight>
</syntaxhighlight>
we can compose conversion sentences like
we can compose conversion sentences like
<lang>
<syntaxhighlight lang="text">
as_degree 100 Gradian
as_degree 100 Gradian
90
90
</syntaxhighlight>
</syntaxhighlight>
Presuming the following additional definitions:
Presuming the following additional definitions:
<lang>
<syntaxhighlight lang="text">
NAMES =: > turn`degree`gradian`mil`radian
NAMES =: > turn`degree`gradian`mil`radian
ALL =: as_turn`as_degree`as_gradian`as_mil`as_radian
ALL =: as_turn`as_degree`as_gradian`as_mil`as_radian
Line 1,863: Line 1,863:


=={{header|Java}}==
=={{header|Java}}==
<syntaxhighlight lang=java>import java.text.DecimalFormat;
<syntaxhighlight lang="java">import java.text.DecimalFormat;


// Title: Angles (geometric), normalization and conversion
// Title: Angles (geometric), normalization and conversion
Line 2,019: Line 2,019:
</pre>
</pre>
=={{header|Javascript}}==
=={{header|Javascript}}==
<syntaxhighlight lang=javaScript>
<syntaxhighlight lang="javascript">
/*****************************************************************\
/*****************************************************************\
| Expects an angle, an origin unit and a unit to convert to, |
| Expects an angle, an origin unit and a unit to convert to, |
Line 2,235: Line 2,235:


'''Preliminaries'''
'''Preliminaries'''
<syntaxhighlight lang=jq>### Formatting
<syntaxhighlight lang="jq">### Formatting


# Right-justify but do not truncate
# Right-justify but do not truncate
Line 2,275: Line 2,275:
</syntaxhighlight>
</syntaxhighlight>
'''The Task'''
'''The Task'''
<syntaxhighlight lang=jq># Normalization as per the task requirements
<syntaxhighlight lang="jq"># Normalization as per the task requirements
def mod($y):
def mod($y):
(if . < 0 then -$y else 0 end) as $adjust
(if . < 0 then -$y else 0 end) as $adjust
Line 2,338: Line 2,338:


=={{header|Julia}}==
=={{header|Julia}}==
<syntaxhighlight lang=julia>using Formatting
<syntaxhighlight lang="julia">using Formatting


d2d(d) = d % 360
d2d(d) = d % 360
Line 2,432: Line 2,432:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=scala>import java.text.DecimalFormat as DF
<syntaxhighlight lang="scala">import java.text.DecimalFormat as DF


const val DEGREE = 360.0
const val DEGREE = 360.0
Line 2,489: Line 2,489:


=={{header|Lua}}==
=={{header|Lua}}==
<syntaxhighlight lang=lua>range = { degrees=360, gradians=400, mils=6400, radians=2.0*math.pi }
<syntaxhighlight lang="lua">range = { degrees=360, gradians=400, mils=6400, radians=2.0*math.pi }
function convert(value, fromunit, tounit)
function convert(value, fromunit, tounit)
return math.fmod(value * range[tounit] / range[fromunit], range[tounit])
return math.fmod(value * range[tounit] / range[fromunit], range[tounit])
Line 2,507: Line 2,507:
end</syntaxhighlight>
end</syntaxhighlight>
Optionally:
Optionally:
<syntaxhighlight lang=lua>-- if you care..
<syntaxhighlight lang="lua">-- if you care..
assert(convert(-360,"degrees","degrees") == 0.0)
assert(convert(-360,"degrees","degrees") == 0.0)
assert(convert(360,"degrees","degrees") == 0.0)
assert(convert(360,"degrees","degrees") == 0.0)
Line 2,586: Line 2,586:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica>ClearAll[NormalizeAngle, NormalizeDegree, NormalizeGradian, NormalizeMil, NormalizeRadian]
<syntaxhighlight lang="mathematica">ClearAll[NormalizeAngle, NormalizeDegree, NormalizeGradian, NormalizeMil, NormalizeRadian]
NormalizeAngle[d_, full_] := Module[{a = d},
NormalizeAngle[d_, full_] := Module[{a = d},
If[Abs[a/full] > 4,
If[Abs[a/full] > 4,
Line 2,621: Line 2,621:


=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang=Nim>import math
<syntaxhighlight lang="nim">import math
import strformat
import strformat


Line 2,737: Line 2,737:
=={{header|Perl}}==
=={{header|Perl}}==
{{trans|Raku}}
{{trans|Raku}}
<syntaxhighlight lang=perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use feature 'say';
use feature 'say';
Line 2,836: Line 2,836:
=={{header|Phix}}==
=={{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
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
<!--<syntaxhighlight lang=Phix>-->
<!--<syntaxhighlight 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: #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>
<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,923: Line 2,923:
=={{header|Python}}==
=={{header|Python}}==
===Python: Original===
===Python: Original===
<syntaxhighlight lang=python>PI = 3.141592653589793
<syntaxhighlight lang="python">PI = 3.141592653589793
TWO_PI = 6.283185307179586
TWO_PI = 6.283185307179586


Line 2,960: Line 2,960:


===Python: using tkinter===
===Python: using tkinter===
<syntaxhighlight lang=python>
<syntaxhighlight lang="python">
''' Python 3.6.5 code using Tkinter graphical user interface.
''' Python 3.6.5 code using Tkinter graphical user interface.
Angles (geometric), normalization and conversion challenge.
Angles (geometric), normalization and conversion challenge.
Line 3,321: Line 3,321:
{{trans|Common Lisp}}
{{trans|Common Lisp}}


<syntaxhighlight lang=racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(define (rem n m)
(define (rem n m)
Line 3,446: Line 3,446:
=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<syntaxhighlight lang=perl6>
<syntaxhighlight lang="raku" line>
my @units =
my @units =
{ code => 'd', name => 'degrees' , number => 360 },
{ code => 'd', name => 'degrees' , number => 360 },
Line 3,543: Line 3,543:
''(Much of the complexity is due to the requirement that negative angles must normalize to a negative number.)''
''(Much of the complexity is due to the requirement that negative angles must normalize to a negative number.)''


<syntaxhighlight lang=perl6>sub postfix:<t>( $t ) { my $a = $t % 1 * τ; $t >=0 ?? $a !! $a - τ }
<syntaxhighlight lang="raku" line>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:<d>( $d ) { my $a = $d % 360 * τ / 360; $d >=0 ?? $a !! $a - τ }
sub postfix:<g>( $g ) { my $a = $g % 400 * τ / 400; $g >=0 ?? $a !! $a - τ }
sub postfix:<g>( $g ) { my $a = $g % 400 * τ / 400; $g >=0 ?? $a !! $a - τ }
Line 3,651: Line 3,651:


=={{header|REXX}}==
=={{header|REXX}}==
<syntaxhighlight lang=rexx>/*REXX pgm normalizes an angle (in a scale), or converts angles from a scale to another.*/
<syntaxhighlight 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.*/
numeric digits length( pi() ) - length(.) /*use the "length" of pi for precision.*/
parse arg x /*obtain optional arguments from the CL*/
parse arg x /*obtain optional arguments from the CL*/
Line 3,769: Line 3,769:
=={{header|Ruby}}==
=={{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.
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.
<syntaxhighlight lang=ruby>module Angles
<syntaxhighlight lang="ruby">module Angles
BASES = {"d" => 360, "g" => 400, "m" => 6400, "r" => Math::PI*2 ,"h" => 24 }
BASES = {"d" => 360, "g" => 400, "m" => 6400, "r" => Math::PI*2 ,"h" => 24 }
Line 3,864: Line 3,864:


=={{header|Rust}}==
=={{header|Rust}}==
<syntaxhighlight lang=rust>use std::{
<syntaxhighlight lang="rust">use std::{
marker::PhantomData,
marker::PhantomData,
f64::consts::PI,
f64::consts::PI,
Line 4,000: Line 4,000:
=={{header|Swift}}==
=={{header|Swift}}==


<syntaxhighlight lang=swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


func normalize(_ f: Double, N: Double) -> Double {
func normalize(_ f: Double, N: Double) -> Double {
Line 4,139: Line 4,139:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|Go}}
{{trans|Go}}
<syntaxhighlight lang=vlang>import math
<syntaxhighlight lang="vlang">import math
import strconv
import strconv
fn d2d(d f64) f64 { return math.mod(d, 360) }
fn d2d(d f64) f64 { return math.mod(d, 360) }
Line 4,199: Line 4,199:
{{trans|Go}}
{{trans|Go}}
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang=ecmascript>import "/fmt" for Fmt
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt


var d2d = Fn.new { |d| d % 360 }
var d2d = Fn.new { |d| d % 360 }
Line 4,299: Line 4,299:


=={{header|XPL0}}==
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0>def Pi = 3.14159265358979323846, N=12, Tab=9;
<syntaxhighlight lang="xpl0">def Pi = 3.14159265358979323846, N=12, Tab=9;
func real D2D; real D; return Mod(D, 360.);
func real D2D; real D; return Mod(D, 360.);
func real G2G; real G; return Mod(G, 400.);
func real G2G; real G; return Mod(G, 400.);
Line 4,421: Line 4,421:
=={{header|zkl}}==
=={{header|zkl}}==
{{trans|Raku}}
{{trans|Raku}}
<syntaxhighlight lang=zkl>var [const]
<syntaxhighlight lang="zkl">var [const]
tau=(0.0).pi*2,
tau=(0.0).pi*2,
units=Dictionary( // code:(name, units in circle)
units=Dictionary( // code:(name, units in circle)
Line 4,436: Line 4,436:
})
})
;</syntaxhighlight>
;</syntaxhighlight>
<syntaxhighlight lang=zkl>codes:=units.keys;
<syntaxhighlight lang="zkl">codes:=units.keys;
println(" Angle Unit ",
println(" Angle Unit ",
codes.apply(fcn(k){ units[k][0] }).apply("%11s".fmt).concat(" "));
codes.apply(fcn(k){ units[k][0] }).apply("%11s".fmt).concat(" "));