Map range: Difference between revisions

17,137 bytes added ,  16 days ago
Added Easylang
m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
(Added Easylang)
 
(36 intermediate revisions by 16 users not shown)
Line 25:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F maprange(a, b, s)
R b[0] + (Float(s - a[0]) * (b[1] - b[0]) / (a[1] - a[0]))
 
L(s) 0..10
print(‘#2 maps to #.’.format(s, maprange((0, 10), (-1, 0), s)))</langsyntaxhighlight>
 
{{out}}
Line 45:
10 maps to 0
</pre>
 
=={{header|6502 Assembly}}==
A range like [0, n] for some natural number <code>n < 255</code> can be easily mapped with a lookup table. The second range can be anything, as long as each entry is the same length and are stored consecutively in the desired order. This method requires a bit of compile-time knowledge, but is very efficient in terms of speed. Each element <code>Bn</code> is stored at relative offset <code>An</code> .
 
<syntaxhighlight lang="6502asm">mapping:
byte $00,$00,$80,$BF ;-1.0f (stored little-endian so the bytes are backwards)
byte $66,$66,$66,$BF ;-0.9f
byte $CD,$CC,$4C,$BF ;-0.8f
byte $33,$33,$33,$BF ;-0.7f
etc.</syntaxhighlight>
 
If the range isn't [0, n], but begins at some other natural number [k, n] where <tt>k,n < 255 </tt>, we can express it as [0, n-k] instead and simply subtract the "key" at runtime to get the offset.
 
This method is very convenient for implementing ASCII into hardware that lacks a built-in system font (like the NES). You can save graphics memory by mapping tile number 0 to ASCII 32, tile number 01 to 33, and so on. Had you mapped them "correctly," (i.e. tile number 32 to ASCII 32) you would still need a "blank tile" as tile number zero. So the easier solution is to subtract 32 from the character code before printing.
 
<syntaxhighlight lang="6502asm">;runs during non-maskable interrupt.
PrintChar:
;a = char to print
SEC
SBC #$32 ;subtract ascii offset to map the index to the correct tile graphics data.
 
;everything below this comment is hardware-specific mumbo-jumbo, feel free to ignore it if you don't care.
;ideally you'd want to do this before getting here so that the only thing that happens during NMI is the write to vram.
pha
LDA Cursor_Y
ASL
ASL
ASL
ASL
ASL
STA tempY ;row * 32
LDA #$20
ADC Cursor_X
STA tempX
LDA $2002 ;reset picture processor high-low latch
LDA tempX
STA $2006 ;this register is big-endian for some reason. Which is why I had to store Cursor_Y << 5 into tempY rather than here directly.
LDA tempY
STA $2006
PLA
STA $2007</syntaxhighlight>
 
=={{header|ACL2}}==
 
<langsyntaxhighlight Lisplang="lisp">(defun mapping (a1 a2 b1 b2 s)
(+ b1 (/ (* (- s a1)
(- b2 b1))
Line 63 ⟶ 104:
;; (-1 -9/10 -4/5 -7/10 -3/5 -1/2 -2/5 -3/10 -1/5 -1/10 0)
 
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
PROC Map(REAL POINTER a1,a2,b1,b2,s,res)
Line 96 ⟶ 137:
PrintRE(res)
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Map_range.png Screenshot from Atari 8-bit computer]
Line 115 ⟶ 156:
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Map is
type First_Range is new Float range 0.0 .. 10.0;
Line 147 ⟶ 188:
Test_Value := Test_Value + 1.0;
end loop;
end Map;</langsyntaxhighlight>
 
{{out}}
Line 163 ⟶ 204:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># maps a real s in the range [ a1, a2 ] to the range [ b1, b2 ] #
# there are no checks that s is in the range or that the ranges are valid #
PROC map range = ( REAL s, a1, a2, b1, b2 )REAL:
Line 171 ⟶ 212:
FOR i FROM 0 TO 10 DO
print( ( whole( i, -2 ), " maps to ", fixed( map range( i, 0, 10, -1, 0 ), -8, 2 ), newline ) )
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 185 ⟶ 226:
9 maps to -0.10
10 maps to 0.00
</pre>
=={{header|Amazing Hopper}}==
La función "Seqspaced" es una macro-sustitución de "seqsp", y está construida, internamente, como una rutina en C que realiza el siguiente cálculo (en pseudocódigo):
<syntaxhighlight lang="c">
double inc = (nHasta - nDesde) / ( nTotal - 1);
lista[0] = nDesde;
lista[nTotal] = nHasta;
for( n=1; n<nTotal; n++){
lista[n] = lista[n-1] + inc;
}
</syntaxhighlight>
Macro-sustitución de "Seqspaced":
<syntaxhighlight lang="amazing hopper">
#defn Seqspaced(__X__,__Y__,__Z__,_V_) #ATOM#CMPLX;#ATOM#CMPLX;#ATOM#CMPLX;keep;lthan(1);\
do{{"Seqspaced: num elements < 1"}throw(2301)},seqsp(_V_)
</syntaxhighlight>
Otras macrosustituciones:
<syntaxhighlight lang="amazing hopper">
#defn Toksep(__X__) #ATOM#CMPLX;toksep;
#defn Cat(_X_,*) #ATOM#CMPLX;#GENCODE $$$*$$$ #ATCMLIST;cat; #ENDGEN
#defn Justleft(_X_,_V_) {" "};#ATOM#CMPLX;#ATOM#CMPLX;padright;
</syntaxhighlight>
Código que resuelve la tarea:
<syntaxhighlight lang="amazing hopper">
#include <jambo.h>
Main
v=0,w=0
Seqspaced(-1,0,11,w) // [-1,0}->[0-10]=11 números
Seqspaced(0,10,11,v)
Toksep( "\n" )
Cat( Justright(5,Str(v))," => ",Justright(5,Str(w))), Prnl
End
</syntaxhighlight>
{{out}}
<pre>
$ hopper maprange.jambo
0 => -1
1 => -0.9
2 => -0.8
3 => -0.7
4 => -0.6
5 => -0.5
6 => -0.4
7 => -0.3
8 => -0.2
9 => -0.1
10 => 0
$
</pre>
 
=={{header|AppleScript}}==
<langsyntaxhighlight lang="applescript">------------------------ MAP RANGE -----------------------
 
-- rangeMap :: (Num, Num) -> (Num, Num) -> Num -> Num
Line 491 ⟶ 580:
return lst
end tell
end zipWith3</langsyntaxhighlight>
{{Out}}
<pre> 0 -> -1.0 = -1/1
Line 507 ⟶ 596:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">getMapped: function [a,b,i][
round .to:1 b\0 + ((i - a\0) * (b\1 - b\0))/(a\1 - a\0)
]
Line 517 ⟶ 606:
mapped: getMapped rangeA rangeB to :floating x
print [x "maps to" mapped]
]</langsyntaxhighlight>
 
{{out}}
Line 535 ⟶ 624:
=={{header|AutoHotkey}}==
{{trans|C}}
<syntaxhighlight lang="autohotkey">
<lang AutoHotkey>
mapRange(a1, a2, b1, b2, s)
{
Line 546 ⟶ 635:
out .= "f(" A_Index-1 ") = " mapRange(0,10,-1,0,A_Index-1) "`n"
MsgBox % out
</syntaxhighlight>
</lang>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f MAP_RANGE.AWK
BEGIN {
Line 564 ⟶ 653:
return b1 + ((num-a1) * (b2-b1) / (a2-a1))
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 582 ⟶ 671:
=={{header|Axiom}}==
Axiom provides a Segment domain for intervals. The following uses a closure for a mapRange function over fields, which provides for some generality.
<langsyntaxhighlight Axiomlang="axiom">)abbrev package TESTP TestPackage
TestPackage(R:Field) : with
mapRange: (Segment(R), Segment(R)) -> (R->R)
Line 588 ⟶ 677:
mapRange(fromRange, toRange) ==
(a1,a2,b1,b2) := (lo fromRange,hi fromRange,lo toRange,hi toRange)
(x:R):R +-> b1+(x-a1)*(b2-b1)/(a2-a1)</langsyntaxhighlight>
Use:<langsyntaxhighlight Axiomlang="axiom">f := mapRange(1..10,a..b)
[(xi,f xi) for xi in 1..10]</langsyntaxhighlight>
{{out}}
<pre> b + 8a 2b + 7a b + 2a 4b + 5a 5b + 4a
Line 603 ⟶ 692:
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<langsyntaxhighlight BASIC256lang="basic256">function MapRange(s, a1, a2, b1, b2)
return b1+(s-a1)*(b2-b1)/(a2-a1)
end function
Line 610 ⟶ 699:
print i; " maps to "; MapRange(i,0,10,-1,0)
next i
end</langsyntaxhighlight>
{{out}}
<pre>
Line 618 ⟶ 707:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> @% = 5 : REM Column width
DIM range{l, h}
DIM A{} = range{}, B{} = range{}
Line 629 ⟶ 718:
DEF FNmaprange(a{}, b{}, s)
= b.l + (s - a.l) * (b.h - b.l) / (a.h - a.l)</langsyntaxhighlight>
{{out}}
<pre>
Line 646 ⟶ 735:
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang="commodorebasic">10 REM MAP RANGE
20 REM COMMODORE BASIC 2.0
30 REM ================================
Line 654 ⟶ 743:
70 FOR S=0 TO 10
80 PRINT S;"MAPS TO ";FN MR(S)
90 NEXT</langsyntaxhighlight>
 
{{out}}
Line 672 ⟶ 761:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "MapRange.bas"
110 LET A1=0:LET A2=10
120 LET B1=-1:LET B2=0
Line 678 ⟶ 767:
140 FOR I=0 TO 10
150 PRINT I;"maps to ";MR(I)
160 NEXT</langsyntaxhighlight>
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">/* map s from [a, b] to [c, d] */
define m(a, b, c, d, s) {
return (c + (s - a) * (d - c) / (b - a))
Line 696 ⟶ 785:
i; " => "; m(0, 10, -1, 0, i)
}
quit</langsyntaxhighlight>
 
{{out}}
Line 718 ⟶ 807:
<code>_map_</code> is a 2-modifier which returns a mapping function given two ranges.
 
<langsyntaxhighlight lang="bqn">_map_ ← {
a1‿a2 _𝕣_ b1‿b2 s:
b1 + ((s - a1) × b2 - b1) ÷ a2 - a1
Line 726 ⟶ 815:
 
•Show ZeroTen 0.1
•Show ZeroTen 8</langsyntaxhighlight>
<langsyntaxhighlight lang="bqn">¯0.99
¯0.19999999999999996</langsyntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=X21hcF8g4oaQIHsKIGEx4oC/YTIgX/CdlaNfIGIx4oC/YjIgczoKIGIxICsgKChzIC0gYTEpIMOXIGIyIC0gYjEpIMO3IGEyIC0gYTEKfQoKWmVyb1RlbiDihpAgMOKAvzEwIF9tYXBfIMKvMeKAvzAKCuKAolNob3cgWmVyb1RlbiAwLjEK4oCiU2hvdyBaZXJvVGVuIDEw Try It!]
=={{header|Bracmat}}==
{{trans|C}}
<langsyntaxhighlight lang="bracmat">( ( mapRange
= a1,a2,b1,b2,s
. !arg:(?a1,?a2.?b1,?b2.?s)
Line 744 ⟶ 833:
& 1+!n:?n
)
);</langsyntaxhighlight>
{{out}}
<pre>Mapping [0,10] to [-1,0] at intervals of 1:
Line 760 ⟶ 849:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
double#define mapRange(double a1,double a2,double b1,double b2,doubles) (b1 + (s-a1)*(b2-b1)/(a2-a1))
{
return b1 + (s-a1)*(b2-b1)/(a2-a1);
}
 
int main()
Line 779 ⟶ 865:
return 0;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 796 ⟶ 882:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
 
Line 807 ⟶ 893:
static double Map(double a1, double a2, double b1, double b2, double s) => b1 + (s - a1) * (b2 - b1) / (a2 - a1);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 827 ⟶ 913:
It's not written efficiently; certainly, there can be fewer explicit temporary variables. The use of the template offers a choice in types for precision and accuracy considerations, though one area for improvement might be to allow a different type for intermediate calculations.
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <utility>
 
Line 852 ⟶ 938:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 872 ⟶ 958:
{{trans|Python}}
 
<langsyntaxhighlight lang="clojure">
(defn maprange [[a1 a2] [b1 b2] s]
(+ b1 (/ (* (- s a1) (- b2 b1)) (- a2 a1))))
Line 890 ⟶ 976:
9 maps to -1/10
10 maps to 0
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. demo-map-range.
 
Line 946 ⟶ 1,032:
/ (a-end - a-begin))
.
END PROGRAM map-range.</langsyntaxhighlight>
 
The output is identical to the output of the Common Lisp example.
Line 952 ⟶ 1,038:
=={{header|CoffeeScript}}==
 
<syntaxhighlight lang="coffeescript ">
<lang CoffeeScript >
mapRange = (a1,a2,b1,b2,s) ->
t = b1 + ((s-a1)*(b2 - b1)/(a2-a1))
Line 958 ⟶ 1,044:
for s in [0..10]
console.log("#{s} maps to #{mapRange(0,10,-1,0,s)}")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 975 ⟶ 1,061:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun map-range (a1 a2 b1 b2 s)
(+ b1
(/ (* (- s a1)
Line 985 ⟶ 1,071:
do (format t "~F maps to ~F~C" i
(map-range 0 10 -1 0 i)
#\Newline))</langsyntaxhighlight>
 
{{out}}
Line 999 ⟶ 1,085:
9.0 maps to -0.1
10.0 maps to 0.0</pre>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">define a1 = 0, b1 = 0, a2 = 0, b2 = 0
 
for i = 0 to 10
 
let s = i
let a1 = 0
let a2 = 10
let b1 = -1
let b2 = 0
 
print i, " : ", b1 + ( s - a1 ) * ( b2 - b1 ) / ( a2 - a1 )
 
next i</syntaxhighlight>
{{out| Output}}<pre>0 : -1
1 : -0.9000
2 : -0.8000
3 : -0.7000
4 : -0.6000
5 : -0.5000
6 : -0.4000
7 : -0.3000
8 : -0.2000
9 : -0.1000
10 : 0</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">double mapRange(in double[] a, in double[] b, in double s)
pure nothrow @nogc {
return b[0] + ((s - a[0]) * (b[1] - b[0]) / (a[1] - a[0]));
Line 1,013 ⟶ 1,125:
foreach (immutable s; 0 .. 11)
writefln("%2d maps to %5.2f", s, mapRange(r1, r2, s));
}</langsyntaxhighlight>
{{out}}
<pre> 0 maps to -1.00
Line 1,028 ⟶ 1,140:
=={{header|Delphi}}==
See [[#Pascal]].
=={{header|EasyLang}}==
<syntaxhighlight>
func map_range a1 a2 b1 b2 s .
return b1 + (s - a1) * (b2 - b1) / (a2 - a1)
.
for i = 0 to 10
print i & " -> " & map_range 0 10 -1 0 i
.
</syntaxhighlight>
{{out}}
<pre>
0 -> -1
1 -> -0.90
2 -> -0.80
3 -> -0.70
4 -> -0.60
5 -> -0.50
6 -> -0.40
7 -> -0.30
8 -> -0.20
9 -> -0.10
10 -> 0
</pre>
 
=={{header|EchoLisp}}==
EchoLisp provides several native interpolation functions: smoothstep, s-curve, .. and '''linear''' which performs linear interpolation.
<langsyntaxhighlight lang="scheme">
(lib 'plot) ;; interpolation functions
(lib 'compile)
Line 1,061 ⟶ 1,197:
8 -1/5 -0.2
9 -1/10 -0.1
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule RC do
def map_range(a1 .. a2, b1 .. b2, s) do
b1 + (s - a1) * (b2 - b1) / (a2 - a1)
Line 1,072 ⟶ 1,208:
Enum.each(0..10, fn s ->
:io.format "~2w map to ~7.3f~n", [s, RC.map_range(0..10, -1..0, s)]
end)</langsyntaxhighlight>
 
{{out}}
Line 1,090 ⟶ 1,226:
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight lang="lisp">(defun maprange (a1 a2 b1 b2 s)
(+ b1 (/ (* (- s a1) (- b2 b1)) (- a2 a1))))
(dotimes (i 10)
(princmessage "%s" (maprange 0.0 10.0 -1.0 0.0 i)))</syntaxhighlight>
(terpri))</lang>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(map_range).
-export([map_value/3]).
 
map_value({A1,A2},{B1,B2},S) ->
B1 + (S - A1) * (B2 - B1) / (A2 - A1).
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM RANGE
 
BEGIN
Line 1,117 ⟶ 1,252:
END FOR
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre> 0 maps to -1.00
Line 1,133 ⟶ 1,268:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function map_range(sequence a, sequence b, atom s)
return b[1]+(s-a[1])*(b[2]-b[1])/(a[2]-a[1])
end function
Line 1,139 ⟶ 1,274:
for i = 0 to 10 do
printf(1, "%2g maps to %4g\n", {i, map_range({0,10},{-1,0},i)})
end for</langsyntaxhighlight>
 
{{out}}
Line 1,154 ⟶ 1,289:
10 maps to 0
</pre>
 
=={{header|F#}}==
<syntaxhighlight lang="fsharp">
let map (a1: float) (a2: float) (b1: float) (b2: float) (s: float): float =
b1 + (s - a1) * (b2 - b1) / (a2 - a1)
 
let xs = [| for i in 0..10 -> map 0.0 10.0 -1.0 0.0 (float i) |]
 
for x in xs do printfn "%f" x
</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USE: locals
:: map-range ( a1 a2 b1 b2 x -- y )
x a1 - b2 b1 - * a2 a1 - / b1 + ;</langsyntaxhighlight>
Or:
<langsyntaxhighlight lang="factor">USING: locals infix ;
:: map-range ( a1 a2 b1 b2 x -- y )
[infix
b1 + (x - a1) * (b2 - b1) / (a2 - a1)
infix] ;</langsyntaxhighlight>
Test run:
<langsyntaxhighlight lang="factor">10 iota [| x | 0 10 -1 0 x map-range ] map . ! { -1 -9/10 -4/5 -7/10 -3/5 -1/2 -2/5 -3/10 -1/5 -1/10 }</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class FRange
{
Line 1,205 ⟶ 1,350:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,223 ⟶ 1,368:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">\ linear interpolation
 
: lerp ( b2 b1 a2 a1 s -- t )
Line 1,231 ⟶ 1,376:
f+ ;
 
: test 11 0 do 0e -1e 10e 0e i s>f lerp f. loop ;</langsyntaxhighlight>
 
There is less stack shuffling if you use origin and range instead of endpoints for intervals. (o = a1, r = a2-a1)
 
<langsyntaxhighlight lang="forth">: lerp ( o2 r2 r1 o1 s -- t ) fswap f- fswap f/ f* f+ ;
 
: test 11 0 do -1e 1e 10e 0e i s>f lerp f. loop ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Map
implicit none
Line 1,261 ⟶ 1,406:
 
end function Maprange
end program Map</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<langsyntaxhighlight lang="freebasic">Function MapRange(s As Integer, a1 As Integer, a2 As Integer, b1 As Integer, b2 As Integer) As Double
Return b1+(s-a1)*(b2-b1)/(a2-a1)
End Function
Line 1,273 ⟶ 1,418:
Print Using "## maps to ##.#"; i; MapRange(i,0,10,-1,0)
Next i
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 1,289 ⟶ 1,434:
</pre>
 
=={{header|Frink}}==
Frink can exactly map to rational numbers so the mapping is round-trippable.
<syntaxhighlight lang="frink">mapRange[s, a1, a2, b1, b2] := b1 + (s-a1)(b2-b1)/(a2-a1)
 
for a = 0 to 10
println["$a\t" + mapRange[a, 0, 10, -1, 0]]</syntaxhighlight>
{{out}}
<pre>
0 -1
1 -9/10 (exactly -0.9)
2 -4/5 (exactly -0.8)
3 -7/10 (exactly -0.7)
4 -3/5 (exactly -0.6)
5 -1/2 (exactly -0.5)
6 -2/5 (exactly -0.4)
7 -3/10 (exactly -0.3)
8 -1/5 (exactly -0.2)
9 -1/10 (exactly -0.1)
10 0
</pre>
 
Much more impressive, though, is that Frink is a powerful Computer Algebra System (CAS) and can symbolically invert the function so you can map t back to s:
 
https://frinklang.org/fsp/solve2.fsp?equations=t+%3D+b1+%2B+%28s-a1%29%28b2-b1%29%2F%28a2-a1%29&solveFor=s&f=on&ev=on&sel_a1=S&val_a1=&sel_a2=S&val_a2=&sel_b1=S&val_b1=&sel_b2=S&val_b2=&sel_t=S&val_t=1000+kg&resultAs=
 
The resulting inverse function is:
<syntaxhighlight lang="frink">inverseMapRange[t, a1, a2, b1, b2] := a1 + a1 b1 (-1 b1 + b2)^-1 + -1 a2 b1 (-1 b1 + b2)^-1 + -1 a1 (-1 b1 + b2)^-1 t + a2 (-1 b1 + b2)^-1 t</syntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn MapRange( s as double, a1 as double, a2 as double, b1 as double, b2 as double ) as double
end fn = b1+(s-a1)*(b2-b1)/(a2-a1)
 
NSInteger i
 
for i = 0 to 10
NSLog( @"%2d maps to %5.1f", i, fn MapRange( i, 0, 10, -1, 0 ) )
next
 
HandleEvents
</syntaxhighlight>
Output:
<pre>
0 maps to -1.0
1 maps to -0.9
2 maps to -0.8
3 maps to -0.7
4 maps to -0.6
5 maps to -0.5
6 maps to -0.4
7 maps to -0.3
8 maps to -0.2
9 maps to -0.1
10 maps to 0.0
</pre>
 
=={{header|GDScript}}==
<syntaxhighlight lang="gdscript">func mapRange(s:float, a1:float, a2:float, b1:float, b2:float) -> float :
return b1 + ((b2-b1)/(a2-a1))*(s-a1)
 
for i in 11 :
print( "%2d %+.1f" % [i,mapRange(i,0.0,10.0,-1.0,0.0)] )
</syntaxhighlight>
 
{{out}}
<pre>
0 -1.0
1 -0.9
2 -0.8
3 -0.7
4 -0.6
5 -0.5
6 -0.4
7 -0.3
8 -0.2
9 -0.1
10 +0.0
</pre>
 
 
=={{header|Go}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn MapRange( s as double, a1 as double, a2 as double, b1 as double, b2 as double ) as double
end fn = b1+(s-a1)*(b2-b1)/(a2-a1)
 
NSInteger i
 
for i = 0 to 10
NSLog( @"%2d maps to %5.1f", i, fn MapRange( i, 0, 10, -1, 0 ) )
next
 
HandleEvents
</syntaxhighlight>
Output:
<pre>
0 maps to -1.0
1 maps to -0.9
2 maps to -0.8
3 maps to -0.7
4 maps to -0.6
5 maps to -0.5
6 maps to -0.4
7 maps to -0.3
8 maps to -0.2
9 maps to -0.1
10 maps to 0.0
</pre>
 
=={{header|Go}}==
'''Basic task'''
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,310 ⟶ 1,566:
fmt.Println(n, "maps to", mapRange(r1, r2, n))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,330 ⟶ 1,586:
Second, ", ok" is a Go idiom. It takes advantage of Go's multiple return values and multiple assignment to return a success/failure disposition.
In the case of this task, the result t is undefined if the input s is out of range.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,366 ⟶ 1,622:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,380 ⟶ 1,636:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">
def mapRange(a1, a2, b1, b2, s) {
b1 + ((s - a1) * (b2 - b1)) / (a2 - a1)
Line 1,388 ⟶ 1,644:
println(s + " in [0, 10] maps to " + mapRange(0, 10, -1, 0, s) + " in [-1, 0].")
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,406 ⟶ 1,662:
=={{header|Haskell}}==
Rather than handling only floating point numbers, the mapping function takes any number implementing the <tt>Fractional</tt> typeclass, which in our example also includes exact <tt>Rational</tt> numbers.
<langsyntaxhighlight lang="haskell">import Data.Ratio
import Text.Printf (PrintfType, printf)
 
Line 1,433 ⟶ 1,689:
:: PrintfType r
=> Integer -> Rational -> r
prtR n x = printf "%2d -> %s\n" n (show x)</langsyntaxhighlight>
{{out}}
<pre>---------- Floating point ----------
Line 1,462 ⟶ 1,718:
=={{header|Icon}} and {{header|Unicon}}==
 
<syntaxhighlight lang="unicon">
<lang Unicon>
record Range(a, b)
 
Line 1,486 ⟶ 1,742:
}
end
</syntaxhighlight>
</lang>
 
Icon does not permit the type declaration, as Unicon does. For Icon, replace 'remap' with:
 
<syntaxhighlight lang="icon">
<lang Icon>
procedure remap (range1, range2, n)
n *:= 1.0
Line 1,496 ⟶ 1,752:
return range1.a + (n - range2.a) * (range1.b - range1.a) / (range2.b - range2.a)
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,515 ⟶ 1,771:
=={{header|J}}==
 
<langsyntaxhighlight lang="j">maprange=:2 :0
'a1 a2'=.m
'b1 b2'=.n
b1+((y-a1)*b2-b1)%a2-a1
)
NB. this version defers all calculations to runtime, but mirrors exactly the task formulation</langsyntaxhighlight>
 
Or
 
<langsyntaxhighlight lang="j">maprange=:2 :0
'a1 a2'=.m
'b1 b2'=.n
b1 + ((b2-b1)%a2-a1) * -&a1
)
NB. this version precomputes the scaling ratio</langsyntaxhighlight>
 
Or, more concisely:<syntaxhighlight lang="j">maprange=:{{ ({.n) + (n%&(-/)m) * -&({.m) }}</syntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> 2 4 maprange 5 11 (2.718282 3 3.141592)
7.15485 8 8.42478</langsyntaxhighlight>
 
or
 
<langsyntaxhighlight lang="j"> adjust=:2 4 maprange 5 11 NB. save the derived function as a named entity
adjust 2.718282 3 3.141592
7.15485 8 8.42478</langsyntaxhighlight>
 
Required example:
 
<langsyntaxhighlight lang="j"> 0 10 maprange _1 0 i.11
_1 _0.9 _0.8 _0.7 _0.6 _0.5 _0.4 _0.3 _0.2 _0.1 0</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class Range {
public static void main(String[] args){
for(float s = 0;s <= 10; s++){
Line 1,559 ⟶ 1,817:
return b1 + ((s - a1)*(b2 - b1))/(a2 - a1);
}
}</langsyntaxhighlight>
{{out}}
<pre>0.0 in [0, 10] maps to -1.0 in [-1, 0].
Line 1,576 ⟶ 1,834:
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight JavaScriptlang="javascript">// Javascript doesn't have built-in support for ranges
// Insted we use arrays of two elements to represent ranges
var mapRange = function(from, to, s) {
Line 1,587 ⟶ 1,845:
}
 
console.log(range);</langsyntaxhighlight>
{{out}}
<pre>[-1, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.30000000000000004, -0.19999999999999996, -0.09999999999999998, 0]</pre>
Line 1,594 ⟶ 1,852:
Here we will use the [https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map ECMAScript 5 support for map] and the [http://underscorejs.org/#range _.range] function from Underscore.js.
{{libheader|Underscore.js}}
<langsyntaxhighlight JavaScriptlang="javascript">var mapRange = function(from, to, s) {
// mapRange expects ranges generated by _.range
var a1 = from[0];
Line 1,612 ⟶ 1,870:
});
 
console.log(fromRange);</langsyntaxhighlight>
{{out}}
<pre>[-1, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.30000000000000004, -0.19999999999999996, -0.09999999999999998, 0]</pre>
Line 1,619 ⟶ 1,877:
 
Composing a solution from generic abstractions:
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,747 ⟶ 2,005:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre> 0 -> -1 = -1/1
Line 1,764 ⟶ 2,022:
In jq, it is generally preferable to define functions as parameterized filters. In the present case,
since the task calls for defining a map, the signature maprange(a;b), where a and b are the two ranges, is appropriate.
<langsyntaxhighlight lang="jq"># The input is the value to be mapped.
# The ranges, a and b, should each be an array defining the
# left-most and right-most points of the range.
def maprange(a; b):
b[0] + (((. - a[0]) * (b[1] - b[0])) / (a[1] - a[0])) ;</langsyntaxhighlight>
'''Example 1''': a single value
6 | maprange([0,10]; [-1, 0])
Line 1,775 ⟶ 2,033:
 
'''Example 2''': a stream of values
<langsyntaxhighlight lang="jq">range(0;11) | maprange([0,10]; [-1, 0])</langsyntaxhighlight>
produces:
-1
Line 1,790 ⟶ 2,048:
====Extra credit====
To avoid repeating the same arithmetic, we shall define a filter that handles an array of values all at once, using an inner function and map/1:
<langsyntaxhighlight lang="jq">def maprange_array(a; b):
def _helper(a0; b0; factor): b0 + (. - a0) * factor;
 
a[0] as $a | b[0] as $b | ((b[1] - b[0]) / (a[1] - a[0])) as $factor
| map(_helper( $a; $b; $factor) );</langsyntaxhighlight>
'''Example''':
[range(0;11)] | maprange_array([0,10]; [-1, 0])
Line 1,801 ⟶ 2,059:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function maprange(s, a, b)
a₁, a₂ = minimum(a), maximum(a)
b₁, b₂ = minimum(b), maximum(b)
Line 1,808 ⟶ 2,066:
 
@show maprange(6, 1:10, -1:0)
@show maprange(0:10, 0:10, -1:0)</langsyntaxhighlight>
 
{{out}}
Line 1,815 ⟶ 2,073:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> f:{[a1;a2;b1;b2;s] b1+(s-a1)*(b2-b1)%(a2-a1)}
 
+(a; f[0;10;-1;0]'a:!11)
Line 1,828 ⟶ 2,086:
(8;-0.2)
(9;-0.1)
(10;0.0))</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
class FloatRange(override val start: Float, override val endInclusive: Float) : ClosedRange<Float>
Line 1,846 ⟶ 2,104:
println(String.format("%2d maps to %+4.2f", i, mappedValue))
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,864 ⟶ 2,122:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def maprange
{lambda {:a0 :a1 :b0 :b1 :s}
Line 1,886 ⟶ 2,144:
9 maps to -0.09999999999999998
10 maps to 0
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define map_range(
a1,
a2,
Line 1,903 ⟶ 2,161:
'<br />'
 
^}'</langsyntaxhighlight>
{{out}}
<pre>0: -1.0
Line 1,918 ⟶ 2,176:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="liberty basic">For i = 0 To 10
Print "f(";i;") maps to ";mapToRange(i, 0, 10, -1, 0)
Next i
Line 1,926 ⟶ 2,184:
mapToRange = (((value - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>f(0) maps to -1
Line 1,941 ⟶ 2,199:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to interpolate :s :a1 :a2 :b1 :b2
output (:s-:a1) / (:a2-:a1) * (:b2-:b1) + :b1
end
 
for [i 0 10] [print interpolate :i 0 10 -1 0]</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function map_range( a1, a2, b1, b2, s )
return b1 + (s-a1)*(b2-b1)/(a2-a1)
end
Line 1,954 ⟶ 2,212:
for i = 0, 10 do
print( string.format( "f(%d) = %f", i, map_range( 0, 10, -1, 0, i ) ) )
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
 
=== Using Class ===
<syntaxhighlight lang="m2000 interpreter">
module MapRange {
class Map {
private:
a, b, f
public:
value (x){
=.b+(x-.a)*.f
}
class:
module Map (.a,a2,.b,b2) {
if a2-.a=0 then error "wrong parameters"
.f<=(b2-.b)/(a2-.a)
}
}
m1=Map(0,10, -1, 0)
for i=0 to 10
Print i," maps to ";m1(i)
next
}
MapRange
</syntaxhighlight>
 
=== Using Lambda ===
 
<syntaxhighlight lang="m2000 interpreter">
module MapRange {
Map=lambda (a,a2,b,b2) -> {
if a2-a=0 then error "wrong parameters"
f=(b2-b)/(a2-a)
=lambda a,b,f (x)->b+(x-a)*f
}
m1=Map(0,10, -1, 0)
for i=0 to 10
Print i," maps to ";m1(i)
next
}
MapRange
</syntaxhighlight>
 
Same output for both versions
 
{{out}}
<pre>
0 maps to -1
1 maps to -0.9
2 maps to -0.8
3 maps to -0.7
4 maps to -0.6
5 maps to -0.5
6 maps to -0.4
7 maps to -0.3
8 maps to -0.2
9 maps to -0.1
10 maps to 0
</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
Map:=proc(a1,a2,b1,b2,s);
return (b1+((s-a1)*(b2-b1)/(a2-a1)));
Line 1,966 ⟶ 2,285:
printf("%a\n",Map(0,10,-1,0,i));
end do;
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Such a function is already built in
<langsyntaxhighlight Mathematicalang="mathematica">Rescale[#,{0,10},{-1,0}]&/@Range[0,10]</langsyntaxhighlight>
{{out}}
<pre>{-1., -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.}</pre>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">maprange(a, b, c, d) := buildq([e: ratsimp(('x - a)*(d - c)/(b - a) + c)],
lambda([x], e))$
 
f: maprange(0, 10, -1, 0);</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 1,998 ⟶ 2,317:
WriteLine("{0, 2:f0} maps to {1:f1}", i, Maprange((0.0, 10.0), (-1.0, 0.0), i));
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 2,021 ⟶ 2,340:
t_ = b1 + ((s_ - a1) * (b2 - b1) / (a2 - a1))
return t_
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,042 ⟶ 2,361:
{{trans|Python}}
 
<langsyntaxhighlight lang="nim">import strformat
 
type FloatRange = tuple[s, e: float]
Line 2,051 ⟶ 2,370:
for i in 0..10:
let m = mapRange((0.0,10.0), (-1.0, 0.0), float(i))
echo &"{i:>2} maps to {m:4.1f}"</langsyntaxhighlight>
 
{{out}}
Line 2,067 ⟶ 2,386:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Range {
Line 2,082 ⟶ 2,401:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,102 ⟶ 2,421:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let map_range (a1, a2) (b1, b2) s =
b1 +. ((s -. a1) *. (b2 -. b1) /. (a2 -. a1))
Line 2,109 ⟶ 2,428:
for i = 0 to 10 do
Printf.printf "f(%d) = %g\n" i (map_range (0.0, 10.0) (-1.0, 0.0) (float i))
done</langsyntaxhighlight>
 
{{out}}
Line 2,127 ⟶ 2,446:
If range mapping is used in a heavy computational task we can reduce the number of calculations made using partial application and [[currying]]:
 
<langsyntaxhighlight lang="ocaml">let map_range (a1, a2) (b1, b2) =
let v = (b2 -. b1) /. (a2 -. a1) in
function s ->
Line 2,137 ⟶ 2,456:
for i = 0 to 10 do
Printf.printf "f(%d) = %g\n" i (p (float i))
done</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: mapRange(p1, p2, s)
s p1 first - p2 second p2 first - * p1 second p1 first - asFloat /
p2 first + ;</langsyntaxhighlight>
 
{{out}}
Line 2,154 ⟶ 2,473:
=={{header|PARI/GP}}==
Usage (e.g.): map([1,10],[0,5],8.)
<langsyntaxhighlight lang="parigp">map(r1,r2,x)=r2[1]+(x-r1[1])*(r2[2]-r2[1])/(r1[2]-r1[1])</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program Map(output);
 
function MapRange(fromRange, toRange: array of real; value: real): real;
Line 2,169 ⟶ 2,488:
for i := 0 to 10 do
writeln (i, ' maps to: ', MapRange([0.0, 10.0], [-1.0, 0.0], i):4:2);
end.</langsyntaxhighlight>
{{out}}
<pre>:> ./MapRange
Line 2,197 ⟶ 2,516:
 
Output as above.
<langsyntaxhighlight lang="pascal">Program Map(output);
 
type
Line 2,252 ⟶ 2,571:
MapRecRange(value,mr):10:6);
end;
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl -w
use strict ;
 
Line 2,267 ⟶ 2,586:
my @interval = ( -1 , 0 ) ;
print "The mapped value for $_ is " . mapValue( \@numbers , \@interval , $_ ) . " !\n" foreach @numbers ;
</syntaxhighlight>
</lang>
{{out}}
<PRE>The mapped value for 0 is -1 !
Line 2,283 ⟶ 2,602:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">map_range</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">a2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b2</span><span style="color: #0000FF;">)</span>
Line 2,292 ⟶ 2,611:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d : %g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">map_range</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,304 ⟶ 2,623:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(scl 1)
 
(de mapRange (Val A1 A2 B1 B2)
Line 2,312 ⟶ 2,631:
(for Val (range 0 10.0 1.0)
(prinl
(format (mapRange Val 0 10.0 -1.0 0) *Scl) ) )</langsyntaxhighlight>
{{out}}
<pre>-1.0
Line 2,327 ⟶ 2,646:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
map: procedure options (main); /* 24/11/2011 */
declare (a1, a2, b1, b2) float;
Line 2,341 ⟶ 2,660:
end map;
end map;
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,360 ⟶ 2,679:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Group-Range
{
Line 2,397 ⟶ 2,716:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
0..10 | Group-Range (0,10) (-1,0)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,419 ⟶ 2,738:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">Structure RR
a.f
b.f
Line 2,441 ⟶ 2,760:
PrintN(RSet(Str(i),2)+" maps to "+StrF(MapRange(@Range1, @Range2, i),1))
Next
EndIf</langsyntaxhighlight>
<pre> 0 maps to -1.0
1 maps to -0.9
Line 2,455 ⟶ 2,774:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> def maprange( a, b, s):
(a1, a2), (b1, b2) = a, b
return b1 + ((s - a1) * (b2 - b1) / (a2 - a1))
Line 2,473 ⟶ 2,792:
8 maps to -0.2
9 maps to -0.1
10 maps to 0</langsyntaxhighlight>
 
Because of Pythons strict, dynamic, typing rules for numbers the same function can give answers as fractions:
<langsyntaxhighlight lang="python">>>> from fractions import Fraction
>>> for s in range(11):
print("%2g maps to %s" % (s, maprange( (0, 10), (-1, 0), Fraction(s))))
Line 2,492 ⟶ 2,811:
9 maps to -1/10
10 maps to 0
>>> </langsyntaxhighlight>
 
=={{header|Quackery}}==
 
As Quackery does not support reals (or floating point), the function takes the argument s as a decimal string, and returns the result, t as a rational number.
 
<syntaxhighlight lang="Quackery"> [ $ "bigrat.qky" loadfile ] now!
 
[ do over -
2swap
do over -
unrot
dip [ $->v drop ]
n->v v-
rot n->v v/
rot n->v v*
rot n->v v+ ] is maprange ( $ [ [ --> n/d )
 
$ "0 1 2 3 4 5 6 7 8 9 10"
nest$
witheach
[ dup echo$ say " maps to "
' [ 0 10 ] ' [ -1 0 ] maprange
7 point$ echo$ cr ]</syntaxhighlight>
 
{{out}}
 
<pre>0 maps to -1
1 maps to -0.9
2 maps to -0.8
3 maps to -0.7
4 maps to -0.6
5 maps to -0.5
6 maps to -0.4
7 maps to -0.3
8 maps to -0.2
9 maps to -0.1
10 maps to 0</pre>
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">tRange <- function(aRange, bRange, s)
{
#Guard clauses. We could write some proper error messages, but this is all we really need.
Line 2,502 ⟶ 2,859:
bRange[1] + ((s - aRange[1]) * (bRange[2] - bRange[1])) / (aRange[2] - aRange[1])
}
data.frame(s = 0:10, t = sapply(0:10, tRange, aRange = c(0, 10), bRange = c(-1, 0)))</langsyntaxhighlight>
{{out}}
<pre> s t
Line 2,519 ⟶ 2,876:
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,530 ⟶ 2,887:
(define map (make-range-map 0 10 -1 0))
(for ([i (in-range 0 11)]) (printf "~a --> ~a\n" i (map i)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,550 ⟶ 2,907:
(formerly Perl 6)
Return a closure that does the mapping without have to supply the ranges every time.
<syntaxhighlight lang="raku" perl6line>sub getmapper(Range $a, Range $b) {
my ($a1, $a2) = $a.bounds;
my ($b1, $b2) = $b.bounds;
Line 2,557 ⟶ 2,914:
 
my &mapper = getmapper(0 .. 10, -1 .. 0);
for ^11 -> $x {say "$x maps to &mapper($x)"}</langsyntaxhighlight>
{{out}}
<pre>0 maps to -1
Line 2,572 ⟶ 2,929:
 
=={{header|ReScript}}==
<langsyntaxhighlight lang="rescript">let map_range = ((a1, a2), (b1, b2), s) => {
b1 +. ((s -. a1) *. (b2 -. b1) /. (a2 -. a1))
}
Line 2,581 ⟶ 2,938:
Js.log("f(" ++ Js.String.make(i) ++ ") = " ++
Js.String.make(map_range((0.0, 10.0), (-1.0, 0.0), float(i))))
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="html"><!DOCTYPE html>
<html>
<head>
Line 2,597 ⟶ 2,954:
 
</body>
</html></langsyntaxhighlight>
 
{{out}}
Line 2,625 ⟶ 2,982:
 
===version 1===
<langsyntaxhighlight lang="rexx">/*REXX program maps and displays a range of numbers from one range to another range.*/
rangeA = 0 10 /*or: rangeA = ' 0 10 ' */
rangeB = -1 0 /*or: rangeB = " -1 0 " */
Line 2,635 ⟶ 2,992:
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
mapR: procedure; parse arg a1 a2,b1 b2,s;$=b1+(s-a1)*(b2-b1)/(a2-a1);return left('',$>=0)$</langsyntaxhighlight>
{{out|output}}
<pre>
Line 2,655 ⟶ 3,012:
 
Note that this REXX version also uses a different &nbsp; '''rangeA''' &nbsp; numbers &nbsp; (they are reversed).
<langsyntaxhighlight lang="rexx">/*REXX program maps and displays a range of numbers from one range to another range.*/
rangeA = 10 0 /*or: rangeA = ' 0 10 ' */
rangeB = -1 0 /*or: rangeB = " -1 0 " */
Line 2,665 ⟶ 3,022:
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
mapR: procedure; parse arg a1 a2,b1 b2,s;$=b1+(s-a1)*(b2-b1)/(a2-a1);return left('',$>=0)$</langsyntaxhighlight>
{{out|output}}
<pre>
Line 2,693 ⟶ 3,050:
===version 3===
This REXX version used a function that calculates and also displays the range mapping.
<langsyntaxhighlight lang="rexx">/*REXX program maps and displays a range of numbers from one range to another range.*/
rangeA = 0 10
rangeB = -1 0
Line 2,705 ⟶ 3,062:
say right(s, 9) ' maps to' left('', t>=0) t
end /*s*/
return /* [↑] LEFT··· aligns non─negative #'s*/</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
===Version 4===
<langsyntaxhighlight lang="rexx">/*REXX program maps a number from one range to another range. */
/* 31.10.2013 Walter Pachl */
/* 'translated' from an older version 1 without using Procedure */
Line 2,718 ⟶ 3,075:
/*──────────────────────────────────MAPRANGE subroutine─────────────────*/
mapRange: return arg(3)+(arg(5)-arg(1))*(arg(4)-arg(3))/(arg(2)-arg(1))
/* Arguments are arg a1,a2,b1,b2,x */</langsyntaxhighlight>
{{out}}
<pre>
Line 2,735 ⟶ 3,092:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Map range
 
Line 2,749 ⟶ 3,106:
func maprange(al, bl, s)
return bl + (s - al) * (bh - bl) / (ah - al)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,763 ⟶ 3,120:
9 maps to -0.1
10 maps to 0
</pre>
 
=={{header|RPL}}==
Ranges are entered as complex numbers to ease input and shorten code
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ → ra rb s
≪ rb ra - DUP RE SWAP IM /
s ra RE - * rb RE +
≫ ≫ 'MAP' STO
|
''( (a1, a2) (b1, b2) s -- t )''
Get (b2 - b1)/(a2 - a1)
Multiply by (s - a1) and add b1
|}
{{in}}
<pre>
(0,10) (-1,0) 0 MAP
(0,10) (-1,0) 4 MAP
(0,10) (-1,0) 10 MAP
</pre>
{{out}}
<pre>
3: -1
2: -0.6
1: 0
</pre>
===Basic RPL code===
No specific data structure, no local variable, full stack calculation. Shorter, but less practical in use and difficult to read.
≪ SWAP 3 PICK -
SWAP 5 PICK - *
ROT 4 ROLL - / +
≫ 'MAP' STO
{{in}}
<pre>
0 10 -1 0 0 MAP
0 10 -1 0 4 MAP
0 10 -1 0 10 MAP
</pre>
{{out}}
<pre>
3: -1
2: -0.6
1: 0
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def map_range(a, b, s)
af, al, bf, bl = a.first, a.last, b.first, b.last
bf + (s - af)*(bl - bf).quo(al - af)
end
 
(0..10).each{|s| puts "%s maps to %g" % [s, map_range(0..10, -1..0, s)]}</langsyntaxhighlight>
 
Numeric#quo does floating point division.
Line 2,790 ⟶ 3,196:
 
To use rational arithmetic, delete <code>s *= 1.0</code> and either <code>require 'rational'</code>, or use Ruby 1.9 (which has Rational in the core library).
<langsyntaxhighlight lang="ruby">(0..10).each do |s|
puts "%s maps to %s" % [s, map_range(0..10, -1..0, s)]
end</langsyntaxhighlight>
 
{{out}} using rational arithmetic:
Line 2,810 ⟶ 3,216:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::f64ops::{Add, Sub, Mul, Div};
 
fn map_range<T: Copy>(from_range: (f64T, f64T), to_range: (f64T, f64T), s: f64T) -> f64T {
where T: Add<T, Output=T> +
Sub<T, Output=T> +
Mul<T, Output=T> +
Div<T, Output=T>
{
to_range.0 + (s - from_range.0) * (to_range.1 - to_range.0) / (from_range.1 - from_range.0)
}
Line 2,822 ⟶ 3,233:
.collect::<Vec<f64>>();
print!("{:?}", result);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,829 ⟶ 3,240:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def mapRange(a1:Double, a2:Double, b1:Double, b2:Double, x:Double):Double=b1+(x-a1)*(b2-b1)/(a2-a1)
 
for(i <- 0 to 10)
println("%2d in [0, 10] maps to %5.2f in [-1, 0]".format(i, mapRange(0,10, -1,0, i)))</langsyntaxhighlight>
{{out}}
<pre> 0 in [0, 10] maps to -1,00 in [-1, 0]
Line 2,847 ⟶ 3,258:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 2,861 ⟶ 3,272:
writeln("f(" <& number <& ") = " <& mapRange(0.0, 10.0, -1.0, 0.0, flt(number)) digits 1);
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,880 ⟶ 3,291:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func map_range(a, b, x) {
var (a1, a2, b1, b2) = (a.bounds, b.bounds);
x-a1 * b2-b1 / a2-a1 + b1;
Line 2,890 ⟶ 3,301:
for x in a {
say "#{x} maps to #{map_range(a, b, x)}";
}</langsyntaxhighlight>
{{out}}
<pre>0 maps to -1
Line 2,904 ⟶ 3,315:
10 maps to 0</pre>
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "mapping" )
@( description, "The task is to write a function/subroutine/... that takes" )
@( description, "two ranges and a real number, and returns the mapping of" )
@( description, "the real number from the first to the second range. Use" )
@( description, "this function to map values from the range [0, 10] to the" )
@( description, "range [-1, 0]." )
@( see_also, "http://rosettacode.org/wiki/Map_range" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
pragma restriction( no_external_commands );
 
procedure mapping is
type first_range is new float;
type second_range is new float;
-- Spar doesn't implement ranges so we'll use constants
first_range_first : constant first_range := 0.0;
first_range_last : constant first_range := 10.0;
second_range_first : constant second_range := -1.0;
second_range_last : constant second_range := 0.0;
 
function translate (first_range_value : first_range) return second_range is
b1 : constant float := float( second_range_first );
b2 : constant float := float( second_range_last );
a1 : constant float := float( first_range_first );
a2 : constant float := float( first_range_last );
result : float;
begin
result := b1 + (float (first_range_value) - a1) * (b2 - b1) / (a2 - a1);
return second_range(result);
end translate;
 
function translate_back (second_range_value : second_range) return first_range is
b1 : constant float := float (first_range_first);
b2 : constant float := float (first_range_last);
a1 : constant float := float (second_range_first);
a2 : constant float := float (second_range_last);
result : float;
begin
result := b1 + (float (second_range_value) - a1) * (b2 - b1) / (a2 - a1);
return first_range (result);
end translate_back;
 
test_value : first_range := first_range_first;
translated_value : second_range;
translated_back_value : first_range;
begin
loop
translated_value := translate( test_value );
translated_back_value := translate_back( translated_value );
 
? strings.image(test_value) & " maps to: "
& strings.image (translated_value);
? strings.image(translated_value) & " maps back to: "
& strings.image (translated_back_value);
exit when test_value = first_range_last;
test_value := @ + 1.0;
end loop;
end mapping;</syntaxhighlight>
{{out}}
<pre>
$ spar mapping.sp
0.0 maps to: -1.00000000000000E+00
-1.00000000000000E+00 maps back to: 0.00000000000000E+00
1.00000000000000E+00 maps to: -9.00000000000000E-01
-9.00000000000000E-01 maps back to: 1.00000000000000E+00
2.00000000000000E+00 maps to: -8.00000000000000E-01
-8.00000000000000E-01 maps back to: 2.00000000000000E+00
3.00000000000000E+00 maps to: -7.00000000000000E-01
-7.00000000000000E-01 maps back to: 3.00000000000000E+00
4.00000000000000E+00 maps to: -6.00000000000000E-01
-6.00000000000000E-01 maps back to: 4.00000000000000E+00
5.00000000000000E+00 maps to: -5.00000000000000E-01
-5.00000000000000E-01 maps back to: 5.00000000000000E+00
6.00000000000000E+00 maps to: -4.00000000000000E-01
-4.00000000000000E-01 maps back to: 6.00000000000000E+00
7.00000000000000E+00 maps to: -3.00000000000000E-01
-3.00000000000000E-01 maps back to: 7.00000000000000E+00
8.00000000000000E+00 maps to: -2.00000000000000E-01
-2.00000000000000E-01 maps back to: 8.00000000000000E+00
9.00000000000000E+00 maps to: -1.00000000000000E-01
-1.00000000000000E-01 maps back to: 9.00000000000000E+00
1.00000000000000E+01 maps to: 0.00000000000000E+00
0.00000000000000E+00 maps back to: 1.00000000000000E+01</pre>
=={{header|Stata}}==
The following program will map a variable to a new variable. It accepts '''if''' and '''in''' conditions.
 
<langsyntaxhighlight lang="stata">program define maprange
version 15.1
syntax varname(numeric) [if] [in], ///
Line 2,928 ⟶ 3,426:
qui gen `generate'=(`varlist'-`a')*`h'+`c' `if' `in'
}
end</langsyntaxhighlight>
 
'''Example'''
 
<langsyntaxhighlight lang="stata">clear
set obs 11
gen x=_n-1
maprange x if mod(x,2)==0, gen(y) from(0 10) to(-10 10)
maprange x if mod(x,2)!=0, gen(y) from(0 10) to(-100 100) replace
list</langsyntaxhighlight>
 
'''Output'''
Line 2,961 ⟶ 3,459:
=={{header|Swift}}==
 
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
func mapRanges(_ r1: ClosedRange<Double>, _ r2: ClosedRange<Double>, to: Double) -> Double {
Line 2,972 ⟶ 3,470:
for i in 0...10 {
print(String(format: "%2d maps to %5.2f", i, mapRanges(0...10, -1...0, to: Double(i))))
}</langsyntaxhighlight>
 
{{out}}
Line 2,989 ⟶ 3,487:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc rangemap {rangeA rangeB value} {
lassign $rangeA a1 a2
lassign $rangeB b1 b2
expr {$b1 + ($value - $a1)*double($b2 - $b1)/($a2 - $a1)}
}</langsyntaxhighlight>
Demonstration (using a curried alias to bind the ranges mapped from and to):
<langsyntaxhighlight lang="tcl">interp alias {} demomap {} rangemap {0 10} {-1 0}
for {set i 0} {$i <= 10} {incr i} {
puts [format "%2d -> %5.2f" $i [demomap $i]]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,017 ⟶ 3,515:
=={{header|Ursala}}==
The function <code>f</code> is defined using pattern matching and substitution, taking a pair of pairs of interval endpoints and a number as parameters, and returning a number.
<langsyntaxhighlight Ursalalang="ursala">#import flo
 
f((("a1","a2"),("b1","b2")),"s") = plus("b1",div(minus("s","a1"),minus("a2","a1")))
Line 3,023 ⟶ 3,521:
#cast %eL
 
test = f* ((0.,10.),(-1.,0.))-* ari11/0. 10.</langsyntaxhighlight>
{{out}}
<pre><
Line 3,038 ⟶ 3,536:
0.000000e+00></pre>
A more idiomatic way is to define f as a second order function
<langsyntaxhighlight Ursalalang="ursala">f(("a1","a2"),("b1","b2")) "s" = ...</langsyntaxhighlight>
with the same right hand side as above, so that it takes a pair of intervals and returns a function mapping numbers in one interval to numbers in the other.
 
Line 3,044 ⟶ 3,542:
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">double map_range(double s, int a1, int a2, int b1, int b2) {
return b1+(s-a1)*(b2-b1)/(a2-a1);
}
Line 3,052 ⟶ 3,550:
print("%2d maps to %5.2f\n", s, map_range(s, 0, 10, -1, 0));
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,070 ⟶ 3,568:
 
=={{header|WDTE}}==
<langsyntaxhighlight WDTElang="wdte">let mapRange r1 r2 s =>
+
(at r2 0)
Line 3,098 ⟶ 3,596:
-> s.map (@ print v => str.format '{} -> {}' (at v 0) (at v 1) -- io.writeln io.stdout)
-> s.drain
;</langsyntaxhighlight>
 
{{out}}
Line 3,114 ⟶ 3,612:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var mapRange = Fn.new { |a, b, s| b.from + (s - a.from) * (b.to - b.from) / (a.to - a.from) }
Line 3,122 ⟶ 3,620:
for (s in a) {
var t = mapRange.call(a, b, s)
var f = Fmt.print(t"$2d >=maps 0)to ?$ h", "s, : ""t)
}</syntaxhighlight>
System.print("%(Fmt.d(2, s)) maps to %(f)%(t)")
}</lang>
 
{{out}}
Line 3,142 ⟶ 3,639:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
func real Map(A1, A2, B1, B2, S);
Line 3,154 ⟶ 3,651:
CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 3,172 ⟶ 3,669:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub MapRange(s, a1, a2, b1, b2)
return b1+(s-a1)*(b2-b1)/(a2-a1)
end sub
Line 3,178 ⟶ 3,675:
for i = 0 to 10 step 2
print i, " : ", MapRange(i,0,10,-1,0)
next</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn mapRange([(a1,a2)], [(b1,b2)], s) // a1a2 is List(a1,a2)
{ b1 + ((s - a1) * (b2 - b1) / (a2 - a1)) }
 
Line 3,187 ⟶ 3,684:
foreach s in ([0.0 .. 10]){
"%2d maps to %5.2f".fmt(s,mapRange(r1,r2, s)).println();
}</langsyntaxhighlight>
{{out}}
<pre>
1,983

edits