Qbasicnews.com

Full Version: Challenge: Algorithms having only one line of code.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3 4 5 6 7 8 9 10
Adding .5 before INT does round to the next integer, the same as CINT does. INT is a floor function. Maybe your original code is in another language?
Yes, the original code was in PICKBasic, which is identical for this one line of code.

What do you mean by a "floor function"?

Have you been able to determine why the formula fails for N=128 without the rounding?
*****
This way works with 128:
Code:
DEFLNG A-Z
a! = LOG(n) / LOG(2)
IF 2 ^ a! = n THEN PRINT n; " is a power of 2"

So i imagine it's a QB bug...

A floor function rounds towars the smaller integer.
I use a replacement for this kind of instruction:

Code:
IF <condition> THEN
   a = <value1>
ELSE
   a = <value2>
END IF

The replacement goes as follows:

Code:
a = (<value1> AND <condition>) + (<value2> AND (NOT <condition>))

Workis well with integer data.
I've got a function for statlib somewhere that does correct rounding (eg .5 and up rounds up, and <.5 rounds down) because the QB ones wern't working for all decimal values. I'll try to find it...
Here's a crappy rounding thingy


N = 3445 ' Number To Round
Dire = 0 ' Direction to round, 1 = Up, 0 = Down

Rounded = CINT(N + ((Dire = 0) - (Dire = 1)) * .5)

PRINT Rounded
this rounds abd is 1 line of code minus the lines that define the variables.

Code:
dec = 1      'how many decimal places to round
num = 2.56   'number to round
PRINT INT(10 ^ dec * num + .5) / 10 ^ dec
This is actually ALauzier's but I just posted it
An excellent example of how a pure logic statement can replace an IF statement.
*****
Let's not forget that positive numbers are rounded UP using .5, and negative numbers are rounded DOWN using -.5.

So, the simplest way is to test the sign of the number to be rounded, and set the rounding factor to .5 or -.5 accordingly. Something like this:
Code:
IF NUMBER < 0 THEN RFACTOR=-.5 ELSE RFACTOR=.5
RESULT=INT(NUMBER+RFACTOR)
*****
Code:
CLS
dec = 2
num = -2.7234
IF NUMBER < 0 THEN rfactor = -.5 ELSE rfactor = .5
PRINT INT(10 ^ dec * num + rfactor) / 10 ^ dec
there
Pages: 1 2 3 4 5 6 7 8 9 10