Simple Math Problem

greencardigan

Senior Member
Hi, I've just run into a little math problem.

I need to read a temp value between a min and max value and then convert it to a value between a different two values.

For example, a temp value of 432 converts to a speed of 50 and a temp value of 480 converts to speed of 200.

I came up with the code below. Is this the best way to go about this??

Code:
SYMBOL MAXTEMP = 480
SYMBOL MINTEMP = 432

SYMBOL MAXSPEED = 200
SYMBOL MINSPEED = 50

SYMBOL TEMP = w1
SYMBOL SPEED = w6

readtemp12 4, TEMP

w2 = MAXTEMP - MINTEMP		'temp range
w3 = MAXSPEED - MINSPEED	'speed range

w4 = w3 / w2			'interger part of ratio

SPEED = TEMP - MINTEMP * w4	'convert integar part

w4 = w3 // w2			'remainder of ratio

SPEED = TEMP - MINTEMP * w4 / w2 + SPEED	'convert remainder part + interger part

SPEED = SPEED + MINSPEED
 

BCJKiwi

Senior Member
Since your mintemp = 432, you could just subtract 432 from that giving you a range of 0 to 48
since you temp range is 200 - 50 = 150, you can then just multiply the 0 to 48 by 3 which gives you 0 to 144 - Close enough?

readtemp12 4, TEMP
Temp = temp - mintemp ' ( 0 through 48)
Speed = temp * 3 + 50
readtemp12 4, TEMP

OR
readtemp12 4, TEMP
Speed = temp - mintemp * 3 + 50

You probably want to make sure you can't get values below zero or too high so improve by using MIN and MAX;

readtemp12 4, TEMP
TEMP = TEMP Min 431 Max 481 'Range of 50
SPEED = TEMP - MINTEMP * 3 + 50 ' 50 to 200
 
Last edited:

greencardigan

Senior Member
It is only a coincidence that the ranges are similar.

I want to be able to change the min and max values without the following code being hard wired.
 

BCJKiwi

Senior Member
There are a variety of ways to achieve this sort of solution.
Perhaps if you gave us the range of input values (temp), and the range of output values (speed) that you want to work with, then we would have a better chance of assisting with something you could use.

The key is to manipulate the math to suit what you want to achieve without losing resolution/accuracy with the integer math issues.
Have a look at the various techniques here;
http://www.picaxeforum.co.uk/showthread.php?t=8624
for dealing with some of these issues.

In terms of dealing with the variations I would think you are on the best path by finding the range of each.

However I'm not sure about the rest without more info.

e.g. If the either range could be the larger you will need to test for that and change the math accordingly.

You need also to consider what happens when you divide and when you take the modulus - unexpected things can happen see notes in the various examples at the above link
 
Top