Shop OBEX P1 Docs P2 Docs Learn Events
Division problem — Parallax Forums

Division problem

TGTG Posts: 36
edited 2008-03-06 00:17 in BASIC Stamp
I am taking two digital channels and counting the pulse length then dividing Sensor1 by Sensor2. Division isn't close when numerator is less than denominator. Any ideas as to what I am missing?

Two examples

Channel Test 1 Test 2
Sensor 1 14264 11152
Sensor 2 12461 12460
STAMP result 1.1441 0.3111
Real result 1.1446 0.89502


' {$STAMP BS2px}
' {$PBASIC 2.5}

Sensor1 PIN 4
Sensor2 PIN 7


S1 VAR Word
S2 VAR Word

TH VAR Word
r VAR Word
qI VAR Byte
qF VAR Word
i VAR Nib

DO
GOSUB Pulse_Test
GOSUB Cal_Ratio
GOSUB Display
LOOP

Pulse_Test:
PULSIN Sensor1,1,S1
PULSIN Sensor2,1,S2
RETURN

Cal_Ratio:
qI = S1 / S2
r = S1 // S2 ' Remainder
qF = 0 ' Clear fractional quotient
FOR i = 1 TO 4 ' Four digits to right of decimal
r = r * 10 ' Multiply remainder by 10
qF = (10 * qF) + (r / S2) ' Multiply quotient by 10 and add
r = r // S2 ' Calculate next remainder
NEXT
IF((r * 10 / S2) >= 5) THEN qF = qF + 1' 5th digit, round up if needed
RETURN

Display:
DEBUG CRSRXY, 0, 1
DEBUG "Sensor1..", DEC5 S1,CLREOL, CR
DEBUG "Sensor2...", DEC5 S2,CLREOL, CR
DEBUG "Cal Ratio...",DEC qI, ".", DEC4 qF, CLREOL, CR
RETURN

Comments

  • Bruce BatesBruce Bates Posts: 3,045
    edited 2008-03-05 22:53
    TG -

    I suspect you will find the answer to your division question here:
    http://www.emesystems.com/BS2math2.htm

    Regards,

    Bruce Bates

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Programming can't be all that difficult, it's nothing but 1's and 0's
  • Tracy AllenTracy Allen Posts: 6,666
    edited 2008-03-06 00:17
    The problem with the algorithm is the multiplication times 10. If the factor is greater than r=6553, then r*10 exceeds 16 bits. And that will happen for some but not all numbers when S2>6553 in the formula, r = S1 // S2.

    Instead of decimal long division, use binary long division. It works for denominators up to 32768:
    www.emesys.com/BS2math2.htm#binary_long
    After the division, convert back to a decmal fraction using the operation, ** 10000.

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Tracy Allen
    www.emesystems.com
Sign In or Register to comment.