Shop OBEX P1 Docs P2 Docs Learn Events
How to best arrange expressions? — Parallax Forums

How to best arrange expressions?

HarleyHarley Posts: 997
edited 2010-08-16 15:19 in Propeller 1
Each item separately evaluates OK, but when combined can even be negative values. Samples can range from 10..200, cursor positions 1 and 2 can be 0..320 and bits is 12 with a clockfreq = 80 million. This to convert on-screen cursor differences to a time value.
    time := (1000 * Samples * (curs2 - curs1) * (1<<bits))/clockfreq   ' in milliseconds

Seems strange what's going on inside the Prop to use all positive values yet get strange values and even negative ones (even when curs2 larger than curs1).

Comments

  • ericballericball Posts: 774
    edited 2010-08-16 11:45
    Your calculation is overflowing 2^31. Assuming max range values:
    time := 2^10 * 2^8 * 2^9 * 2^ 12 / 2^26
    time := 2^(10 + 8 + 9 + 12) / 2^26
    time := 2^(39) / 2^26
    

    Instead do :
    time := Samples * (curs2 - curs1) * (1<<bits)/(clockfreq/1000)   ' in milliseconds
    
    That will keep everything in range.
  • HarleyHarley Posts: 997
    edited 2010-08-16 12:29
    Thanks, ericball. I'd not needed to work such things out before. I see how you approximated the 'powers of 2' and spotted the problem.

    Yes, that cleared up the problem beautifully. Greater than 2^31 and the world goes negative. And what was strange was moving one or the other cursor slight amounts would display strange results, values not varying as expected, positive or negative values for slight movements.
  • JasonDorieJasonDorie Posts: 1,930
    edited 2010-08-16 12:43
    One additional note,

    If you make the assumption that clkfreq will be constant, you can replace (clkfreq/1000) with constant(80_000_000/1000) in the code. That will make the SPIN compiler evaluate it, instead of doing it in your running code. The result is a faster program.

    If 'bits' is constant, you can do the same for it. The end result would look like this:
    time := Samples * (curs2 - curs1) * constant(1<<bits)/constant(80000000/1000) ' in ms
    

    The standard SPIN compiler doesn't make any attempt to optimize constant portions of an expression, but you can do it by hand.

    Jason
  • HarleyHarley Posts: 997
    edited 2010-08-16 15:19
    JasonDorie, thank you also for that approach to making solutions more easily organized. So may ways to get the crud out of the way.
Sign In or Register to comment.