Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Wednesday, March 13, 2013

The Zen of Python, by Tim Peters (python -m this)

$ python -m this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Wednesday, March 23, 2011

What is absolute value of Integer.MIN_VALUE ?

what does below code return?

[java]
int ret = Math.abs(Integer.MIN_VALUE);
[/java]

In the number system, there are more negative numbers than positive ones. Not all -ve numbers have their positive counterparts (e.g. -3 & +3). Ignoring 0. The minimum possible number in 32 bit number is 10000000000000000000000000000000(31 zeroes, say 1000...0).

Here is how absolute value is calculated.

we take Two's compliment by inverting the whole number (replace 1 with 0 and 0 with 1) and then add 1 to the final value.

Lets do it together:
in 2*32 bit number... 1000...0 is -ve

1) 2s compliment would be:

~100000...0 = 011111...1

2) add 1, would become 01111...11 + 1 = 1000000...0

so its back to the same number Integer.MIN_VALUE

Absolute value of MIN_VALUE is itself.

[java]
Integer.MIN_VALUE = Math.abs(Integer.MIN_VALUE)
[/java]

Note: Math.abs(...) doesn't guarantee to always return positive number. The same is true for "%" operator as it gives remainder but not modulo. Remainder could be negative.