Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Challenge: Algorithms having only one line of code.
#51
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?
Antoni
Reply
#52
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?
*****
Reply
#53
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.
Antoni
Reply
#54
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.
SCUMM (the band) on Myspace!
ComputerEmuzone Games Studio
underBASIC, homegrown musicians
[img]http://www.ojodepez-fanzine.net/almacen/yoghourtslover.png[/i
Reply
#55
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...
Reply
#56
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
very F***ing song remains the same
To everyone who sucks-up for the fame
Out of strength you know we speak the truth
Every trend that dies is living proof

MasterMinds Software
Reply
#57
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
[Image: sig.php]
Back by popular demand!
I will byte and nibble you bit by bit until nothing remains but crumbs.
Reply
#58
An excellent example of how a pure logic statement can replace an IF statement.
*****
Reply
#59
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)
*****
Reply
#60
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
[Image: sig.php]
Back by popular demand!
I will byte and nibble you bit by bit until nothing remains but crumbs.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)