How to resolve the algorithm Map range step by step in the OCaml programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Map range step by step in the OCaml programming language
Table of Contents
Problem Statement
Given two ranges: where:
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range [0, 10] to the range [-1, 0].
Show additional idiomatic ways of performing the mapping, using tools available to the language.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Map range step by step in the OCaml programming language
Source code in the ocaml programming language
let map_range (a1, a2) (b1, b2) s =
b1 +. ((s -. a1) *. (b2 -. b1) /. (a2 -. a1))
let () =
print_endline "Mapping [0,10] to [-1,0] at intervals of 1:";
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
let map_range (a1, a2) (b1, b2) =
let v = (b2 -. b1) /. (a2 -. a1) in
function s ->
b1 +. ((s -. a1) *. v)
let () =
print_endline "Mapping [0,10] to [-1,0] at intervals of 1:";
let p = (map_range (0.0, 10.0) (-1.0, 0.0)) in
for i = 0 to 10 do
Printf.printf "f(%d) = %g\n" i (p (float i))
done
You may also check:How to resolve the algorithm N-queens problem step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Euler's sum of powers conjecture step by step in the Tcl programming language
You may also check:How to resolve the algorithm Literals/Integer step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Multiple distinct objects step by step in the Rust programming language
You may also check:How to resolve the algorithm Five weekends step by step in the NetRexx programming language