Mini 3: Map(-range)
author |
Steve Losh <steve@stevelosh.com> |
date |
Tue, 12 Apr 2016 22:05:57 +0000 |
parents |
4b895fc69daf |
children |
4e226f02861b |
(in-package #:coding-math)
;; Constants
(defconstant tau (* pi 2))
;; Number range mapping
(defun normalize (min max val)
(/ (- val min)
(- max min)))
(defun lerp (from to n)
"Lerp together `from` and `to` by factor `n`.
Note that you might want `precise-lerp` instead.
"
(+ from
(* n (- to from))))
(defun precise-lerp (from to n)
"Lerp together `from` and `to` by factor `n`, precisely.
Vanilla lerp does not guarantee `(lerp from to 0.0)` will return exactly
`from` due to floating-point errors. This version will return exactly `from`
when given a `n` of `0.0`, at the cost of an extra multiplication.
"
(+ (* (- 1 n) from)
(* n to)))
(defun map-range (source-from source-to dest-from dest-to source-val)
"Map `source-val` from the source range to the destination range."
(lerp dest-from dest-to
(normalize source-from source-to source-val)))