title: How can I wrap a given number within a given [range)?
body: <p>I'm trying to write a function which wraps an input value within an input range (inclusive lower-bound, exclusive upper-bound), so that the output value is always within that range.</p>
  <p>For example, <code>4.9.wrapped(within: 3..&lt;5) == 4.9</code>, and <code>5.wrapped(within: 3..&lt;5) == 3</code>.<br/>
  (<code>3..&lt;5</code> is Swift syntax for <code>[3, 5)</code>).</p>
  <p>I wrote the below algorithm, which <em>almost</em> works perfectly, except when the input value is less than the lower-bound of the input range, then the output's inclusivity flips.</p>
  <p>For example, when the input range is <code>[3, 5)</code> and the input value is <code>20</code>, then the range output correctly reflects as <code>[3, 5)</code> in the output, but when the input value is <code>1</code> with the same input range, then the output incorrectly reflects a <code>(3, 5]</code> range.</p>
  <h3>Example code in Swift</h3>
  <pre class="lang-swift prettyprint-override"><code>public extension FloatingPoint {
      
      func wrapped(within range: Range&lt;Self&gt;) -&gt; Self {
          
          let breadth = range.upperBound - range.lowerBound
          
          let offset: Self 
          if self &lt; range.lowerBound {
              offset = breadth
          }
          else {
              offset = 0
          }
          
          let baseResult = (self - range.lowerBound).truncatingRemainder(dividingBy: breadth)
  
          return baseResult + range.lowerBound + offset
      }
  }
  </code></pre>
  <h3>Example code as pseudocode</h3>
  <pre><code>function (value: Number, rangeLowerBoundInclusive: Number, rangeUpperBoundExclusive: Number) returns Number {
  
      let breadth be (rangeUpperBoundExclusive - rangeLowerBoundInclusive)
  
      if (value is less than rangeLowerBoundInclusive)
          let offset be breadth
      else
          let offset be 0
  
      let baseResult be ((value - rangeLowerBoundInclusive) mod breadth)
      
      return baseResult + rangeLowerBoundInclusive + offset
  }
  </code></pre>
  <h3>Output Visualization</h3>
  <p>Here is a visualization of the output for all input values from <code>-10</code> to <code>10</code>, stepping <code>0.1</code> at a time, with the range <code>[3, 5)</code>:</p>
  <p><a href="https://i.stack.imgur.com/MdMUh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MdMUh.png" alt="A sawtooth graph, showing the incorrect behavior described by this question." /></a></p>
  <p>As you can see, the input values less than <code>3.0</code> all appear within the range <code>(3, 5]</code>, and the input values greater than or equal to <code>3.0</code> all appear within the range <code>[3, 5)</code>. <strong>Why is this, and how can I make it so that all values are within <code>[3, 5)</code>?</strong></p>