Absolute Val for Integers?
Posted: Sun Jan 20, 2019 11:23 am
I notice that ABS(number) is only for floating point is there such a function for integers?
CD
CD
http://www.purebasic.com
https://www.purebasic.fr/english/
Code: Select all
n.i = -1234567890
Debug Abs(n) ; Shows 1234567890.0
Code: Select all
y = 100
z = 110564567689766987
x = y - z
Debug Abs(x)
Code: Select all
Debug Abs(-100000000000000001)
Code: Select all
Procedure.q AbsI(Value.q)
If Value < 0
ProcedureReturn -Value
Else
ProcedureReturn Value
EndIf
EndProcedure
Debug AbsI(-100000000000000001)
Code: Select all
y = -457
If y < 0
y = y - (2 * y)
EndIf
Debug y
And why doesn't do Pb this by itself? Shouldn't be so complicated that Abs () automatically detects whether it is an integer or a float.STARGÅTE wrote: You have to define your own procedure:Code: Select all
Procedure.q AbsI(Value.q) If Value < 0 ProcedureReturn -Value Else ProcedureReturn Value EndIf EndProcedure Debug AbsI(-100000000000000001)
Code: Select all
#iAbs = $7FFFFFFFFFFFFFFF
...
...
MyInteger & #iAbs
Code: Select all
Procedure.Q qAbs(A.Q)
! Xor RAX, RAX
! Add RAX, [p.v_A] ; let's define A
! Ja l_cancelabs ; positive? yes : cancel
; else
! Xor RAX, 0xFFFFFFFFFFFFFFFF ; A ! (-1)
! Add RAX, 1 ; A + 1
cancelabs:
ProcedureReturn
EndProcedure
Agreed, but at least you don't have to resort to the Windows API to fix this.Josh wrote:And why doesn't do Pb this by itself?
PB's casting rules are a bit special sometimes. If you pass an expression with a division to Abs() then PB would have to decide on some rules if, or if not, an integer division is done and/or integer or float Abs() is to be called etc., at least i think it's something in that direction.Josh wrote:And why doesn't do Pb this by itself? Shouldn't be so complicated that Abs () automatically detects whether it is an integer or a float.
Does PB offer you the posibility to have one procedure parameter which can reperesent different types?Josh wrote:And why doesn't do Pb this by itself? Shouldn't be so complicated that Abs () automatically detects whether it is an integer or a float.
There are already several threads here on the forum about Abs() for integers, including feature requests:Olliv wrote:maybe write on wishlist to have a native AbsI().
I just wanted to say that this has already been requested (at least) twice. That's all.Olliv wrote:maybe write on wishlist to have a native AbsI().
Code: Select all
;Windows x64
If OpenLibrary(0, "msvcrt.dll")
Prototype.q Abs64(V1.q)
Prototype.l Abs32(V2.l)
Abs64.Abs64 = GetFunction(0, "_abs64")
Abs32.Abs32 = GetFunction(0, "labs")
CloseLibrary(0)
Else
;Error
EndIf
y1.q = 100
z1.q = 110564567689766987
x1.q = y1 - z1
Debug Abs64(x1)
y2.l = 100
z2.l = 110564567
x2.l = y2 - z2
Debug Abs32(x2)