Map Number to Range

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In programming, we often need to map a number from one range to another range. For example, we may have a number that ranges from 0 to 10, but we need to map it to a range of 0 to 100. This can be useful in many applications, such as scaling data or converting units.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13700{{"`Map Number to Range`"}} python/variables_data_types -.-> lab-13700{{"`Map Number to Range`"}} python/numeric_types -.-> lab-13700{{"`Map Number to Range`"}} python/type_conversion -.-> lab-13700{{"`Map Number to Range`"}} python/tuples -.-> lab-13700{{"`Map Number to Range`"}} python/function_definition -.-> lab-13700{{"`Map Number to Range`"}} python/build_in_functions -.-> lab-13700{{"`Map Number to Range`"}} end

Map Number to Range

Write a function called num_to_range that takes five arguments: num, inMin, inMax, outMin, and outMax. The function should return num mapped between outMin-outMax from inMin-inMax. In other words, the function should take a number (num) that falls within a certain range (inMin-inMax) and map it to a new range (outMin-outMax).

def num_to_range(num, inMin, inMax, outMin, outMax):
  return outMin + (float(num - inMin) / float(inMax - inMin) * (outMax
                  - outMin))
num_to_range(5, 0, 10, 0, 100) ## 50.0

Summary

In this challenge, you were asked to write a function that maps a number from one range to another range. This can be a useful tool in many programming applications.

Other Python Tutorials you may like