Hey again esteemed Monks,

I've got yet another mathematical question which once again, should be quite easy.

I'm adding a digital potentiometer to my Raspberry Pi CI unit test platform. This pot has 256 taps (0-255). (If you're unsure what a potentiometer is, imagine in the old days where you had to turn up/down your radio volume with a knob).

For my tests, I'm looking to normalize the 256 taps to a value between 0 and 100 (percent). I've been looking online to sort this out and I'm sure I've got it, but there are so many answers, I thought I'd reach out here to ensure things appear correct:

use warnings; use strict; use feature 'say'; my ($min, $max) = (0, 255); my ($new_min, $new_max) = (0, 100); for my $tap ($min .. $max){ my $x = (($tap - $min) * ($new_max - $new_min) / ($max - $min)); say "$tap: $x"; }

Output:

0: 0 1: 0.392156862745098 2: 0.784313725490196 3: 1.17647058823529 ... 127: 49.8039215686275 128: 50.1960784313725 129: 50.5882352941176 ... 252: 98.8235294117647 253: 99.2156862745098 254: 99.6078431372549 255: 100

It appears perfectly good to me for what I need it for, but just would like some reassurance, so that if I use this calculation in the future, I won't be wondering what may be wrong.

When I'm testing variable outputs from such Integrated Circuits (pots, digital to analog converters etc), I want to set up a normalized number range and test each point (within a 1-2% boundary) instead of jumping chunks using AoAs for the data ranges to test against, like I do here.

Do my calculations within the code resonate well?


In reply to Normalizing a range of numbers to a percentage by stevieb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.