proving floor, and rounding floats in some programming languages

35 Views Asked by At

Here is a simple property which is very useful while programming :

In most programming languages,

int(float)=floor(float) for positive values, remove decimals for negative values

for example (Python)

k=2.62
int(k)//will give 2 (floor)
int(k+0.5) // will give int(3.12) ie : 3 

Supposing there is no rouding errors by the way

Here is what I intended to do to prove this property, Let $E$ denote the floor function and $D$ the decimal fraction ie : $D(x)=x-E(x)$

I want to prove that

$$D(x)\geq 0.5 \implies E(x+0.5)=E(x)+1$$

for positive decimal numbers

By definition of $E(x)$ we have :

$$E(x+0.5)\leq E(x)+1$$ $$0.5\leq (x+0.5)-E(x+0.5)<1$$ But from there I'm stuck, any help would therefore be appreciated

Thanks!

1

There are 1 best solutions below

2
On BEST ANSWER

You need to know the following properties of $E(x)$: for all real $x$, $x-1<E(x)\le x$ and $E(x)\le x\lt E(x)+1$. Otherwise see this.


$E(x+0.5)$ is never equal to $x+1$. On one hand, $x$ would need to be an integer, but then $E(x+0.5)$ would be equal to $x$.

But you probably mean this:

$D(x)\ge0.5$ is equivalent to $x-E(x)\ge0.5$. But then $x\ge E(x)+0.5$, hence $x+0.5\ge E(x)+1$ and $E(x+0.5)\ge E(E(x)+1)=E(x)+1$.

On the other hand, $E(x+0.5)\le x+0.5<E(x)+1+0.5<E(x)+2$.

Hence, if $D(x)\ge0.5$,

$$E(x+0.5)=E(x)+1$$


A warning though: when you write int(x)=floor(x), this is usually only valid for $x\ge0$. Often, int(x) rounds toward zero, while floor(x) rounds towards $-\infty$. For instance, in Python, int(-2.3) is $-2$, while floor(-2.3) is $-3$.