Options for rounding numbers

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
BackupUser
PureBasic Guru
PureBasic Guru
Posts: 16777133
Joined: Tue Apr 22, 2003 7:42 pm

Post by BackupUser »

Restored from previous forum. Originally posted by tinman.

Hi,

Would it be possible to add a command for setting the way floating point numbers are rounded when you transfer them to integers? Every language I have ever used simply cuts off the fraction, which I find most useful (of course, I can see that it could be handy to have it rounded to the nearest integer, but I have never needed that case personally).

I know you can use Round(x,0) but isn't this slower than simply x.w=y.f (since it has to go to the hassle of calling a command, whereas the assignment can be done inline).

Something like this perhaps:

RoundMode -1 ; always round down
RoundMose 0 ; round to nearest integer - default setting
RoundMode 1 ; always round up

I've also noticed that a float with a value of .5 always rounds down, whereas mathematically you would round this up. I'm willing to accept that this is is a problem of floating point accuracy though.

Thanks.


--
It's not minimalist - I'm increasing efficiency by reducing input effort.
BackupUser
PureBasic Guru
PureBasic Guru
Posts: 16777133
Joined: Tue Apr 22, 2003 7:42 pm

Post by BackupUser »

Restored from previous forum. Originally posted by El_Choni.

THis is the asm output produced both ways:

Code: Select all

; w.w
; f.f = 2.3
  MOV    dword [v_f],1075000115
; w = f
  FLD    dword [v_f]
  PUSH   eax
  FISTP  dword [esp]
  POP    eax
  MOV    word [v_w],ax
; w = Round(f, 0)
  PUSH   dword 0
  PUSH   dword [v_f]
  CALL  _PB_Round@8
  PUSH   eax
  FISTP  dword [esp]
  POP    eax
  MOV    word [v_w],ax
The 'assign' way is obviously faster, but the way rounding is done depends on the FPU. Anyway, FPU rounding mode can be changed, so I think your suggestion for a RoundMode() command is a good idea.

Bye,

El_Choni

Edited by - El_Choni on 28 April 2002 19:09:20
BackupUser
PureBasic Guru
PureBasic Guru
Posts: 16777133
Joined: Tue Apr 22, 2003 7:42 pm

Post by BackupUser »

Restored from previous forum. Originally posted by El_Choni.

Added RoundMode() to the MathExtras library (should be available at Paul's site in 24 hours):

http://www.reelmediaproductions.com/pb

Hope it helps (it doesn't use the values you suggested, but the values used by the FPU, for speed's sake).

El_Choni
BackupUser
PureBasic Guru
PureBasic Guru
Posts: 16777133
Joined: Tue Apr 22, 2003 7:42 pm

Post by BackupUser »

Restored from previous forum. Originally posted by tinman.

I figured the rounding mode would be controlled by the fpu, but I wasn't exactly sure (I think the 68k acts in the same way, didn't know about x86).
Added RoundMode() to the MathExtras library (should be available at Paul's site in 24 hours):
Cool :)


--
It's not minimalist - I'm increasing efficiency by reducing input effort.
Post Reply