Extrange problem with map function???

Hello to all, I write this because I'm having an extrange problem (at least I think so) with the "map" function. Please let me explain:

I have the following variables:

unsigned long encoderValue = 0;
unsigned long encoderMax = 999000;
unsigned long setValue = 0;
unsigned long setValueB = 0;

encoderValue is a variable where I store the "position" of a rotary encoder, from 0 to encoderMax (990000).

I need to "map" this range of values to 0-4095, because I need to set the input of a 12 bit DAC (MCP4725), so I decide to use
the map function in the following way:

setValue = map(encoderValue, 0, 999000, 0, 4095);

But the problem is that when encoderValue is greater than 524417 the setValue becomes incorrect. In numbers:

encoderValue = 37990 ---> setValue = 278
encoderValue = 368990 ---> setValue = 1516
encoderValue = 399000 ---> setValue = 2045
encoderValue = 524417 ---> setValue = 2149
encoderValue = 524417 ---> setValue = 4294965147
encoderValue = 731418 ---> setValue = 4294965954
encoderValue = 901418 ---> setValue = 4294966651
encoderValue = 999000 ---> setValue = 4294967092

But if instead of the map function I use:

setValue = encoderValue * 4095 / 999000;

Or even (as the map function is defined in the documentation):

setValue = (encoderValue - 0) * (4095 - 0) / (999000 - 0) + 0;

The setValue variable always has the correct value! From 0 to 4095. So, I honestly don't undersatnd what is hapening.

There is no big problem in use setValue = encoderValue * 4095 / 999000, but I really want to understand what is wrong here, so I
would really appreciate your help.

Thanks a lot and best regards,

Mauro.

Look at the documentation for the map() function. It uses 32-bit 'long' integers internally. I suspect that your large numbers have overflowed the internal storage.

Make your own map function:

long myMap(x, x1, x2, y1, y2) {
  return map(x/256, x1/256, x2/256, y1, y2);
}

The map() function works with signed long values, and a value of 524417 causes it to overflow. Your "manual" calculation works with unsigned long values, which doesn't ever overflow with the numbers you have to work with.