Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I map numbers in C# like with map in Arduino?

Tags:

c#

arduino

Is there a function like Arduino's map in C#?

like image 366
jM2.me Avatar asked Jan 16 '13 07:01

jM2.me


People also ask

How do you map a value to another value?

How do you map a value to another value? If you need to map or translate inputs to arbitrary values, you can use the VLOOKUP function. Since there is no way to derive the output (i.e. it's arbitrary), we need to do some kind of lookup. The VLOOKUP function provides an easy way to do this.

What is map function C?

Maps are part of the C++ STL (Standard Template Library). Maps are the associative containers that store sorted key-value pair, in which each key is unique and it can be inserted or deleted but cannot be altered. Values associated with keys can be changed.

What is the limitation of the map () function?

The map() function uses integer math so will not generate fractions, when the math might indicate that it should do so. Fractional remainders are truncated, and are not rounded or averaged.

How do I map a number in Python?

Python map() functionmap() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.


1 Answers

You can do it with an Extension Method (for decimal for example):

public static class ExtensionMethods
{
    public static decimal Map (this decimal value, decimal fromSource, decimal toSource, decimal fromTarget, decimal toTarget)
    {
        return (value - fromSource) / (toSource - fromSource) * (toTarget - fromTarget) + fromTarget;
    }
}

Then you can use it like:

decimal res = 2.Map(1, 3, 0, 10);
// res will be 5
like image 118
Yannick Blondeau Avatar answered Oct 02 '22 15:10

Yannick Blondeau