473,785 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

GetHashCode returns the same value for two doubles

Dan
Hi,

I did a test in C#

double x1 = 1.0;
double x2 = 5.2998088236266 4E-315;
int h1 = x1.GetHashCode( );
int h2 = x2.GetHashCode( );

It turned out that both h1 and h2 = 1072693248

It is not unique! Is it a defect?
Thanks.

Dan

Nov 17 '05 #1
8 5797
See
http://msdn.microsoft.com/library/de...hcodetopic.asp

In the Remarks it says:

"The default implementation of GetHashCode does not guarantee uniqueness or
consistency; therefore, it must not be used as a unique object identifier
for hashing purposes. Derived classes must override GetHashCode with an
implementation that returns a unique hash code."

So; it's not a "defect" per say.

Shariq
sh****@shariqkh an.com

"Dan" <da*****@canada .com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Hi,

I did a test in C#

double x1 = 1.0;
double x2 = 5.2998088236266 4E-315;
int h1 = x1.GetHashCode( );
int h2 = x2.GetHashCode( );

It turned out that both h1 and h2 = 1072693248

It is not unique! Is it a defect?
Thanks.

Dan

Nov 17 '05 #2
Dan <da*****@canada .com> wrote:
I did a test in C#

double x1 = 1.0;
double x2 = 5.2998088236266 4E-315;
int h1 = x1.GetHashCode( );
int h2 = x2.GetHashCode( );

It turned out that both h1 and h2 = 1072693248

It is not unique! Is it a defect?


How could all doubles have unique hashcodes? There are more doubles
than there are ints.

Anything which relies on two semantically different values having
different hashcodes is broken.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3
hi,
every time it calculates 1072693248 for x1 and x2. but x2 has a special
value.
For instance;
x2+1.0= ?
answer is quite surprising: 1.0
for x2=2.0 it calculates 1073741824
difference it is 1048576=1024*10 24
there are 1048576 distinct values. Hashing function simply calculates in
this way...

--

Thanks,
Yunus Emre ALPÖZEN
BSc, MCAD.NET

"Dan" <da*****@canada .com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
Hi,

I did a test in C#

double x1 = 1.0;
double x2 = 5.2998088236266 4E-315;
int h1 = x1.GetHashCode( );
int h2 = x2.GetHashCode( );

It turned out that both h1 and h2 = 1072693248

It is not unique! Is it a defect?
Thanks.

Dan

Nov 17 '05 #4
Yunus Emre ALPÖZEN [MCAD.NET] <ye***@msakadem ik.net> wrote:
hi,
every time it calculates 1072693248 for x1 and x2. but x2 has a special
value.
For instance;
x2+1.0= ?
answer is quite surprising: 1.0
for x2=2.0 it calculates 1073741824
difference it is 1048576=1024*10 24
there are 1048576 distinct values. Hashing function simply calculates in
this way...


That's quite a leap of logic there...

Here's a counterexample - this class just generates random doubles and
checks whether or not the hashcode has already been seen:

using System;
using System.Collecti ons;

class Test
{
static void Main()
{
Hashtable map = new Hashtable();
Random rng = new Random();

int distinct = 0;
while (true)
{
double d = rng.Next();

int hash = d.GetHashCode() ;
if (!map.ContainsK ey(hash))
{
map[hash]=hash;
distinct++;
if (distinct % 1000==0)
{
Console.WriteLi ne (distinct);
}
}
}
}
}

It doesn't take it long to go over the number of distinct values you
claim.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5
Could not understand what u mean ???

I made several changes on your code:

using System;
using System.Collecti ons;

class Test
{
static void Main()
{
Hashtable map = new Hashtable();
Random rng = new Random();

int distinct = 0;
int same = 0;
while (true)
{
double d = rng.Next();

int hash = d.GetHashCode() ;
if (!map.ContainsK ey(hash))
{
map[hash]=d;
distinct++;
if (distinct % 1000==0)
{
//Console.WriteLi ne (distinct);
}
}
else
{
if (((double)map[hash])!=d)
{
same++;
Console.WriteLi ne("{0}\t{1}",d ,map[hash]);
}
}
}
}
}
--

Thanks,
Yunus Emre ALPÖZEN
BSc, MCAD.NET

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Yunus Emre ALPÖZEN [MCAD.NET] <ye***@msakadem ik.net> wrote:
hi,
every time it calculates 1072693248 for x1 and x2. but x2 has a special
value.
For instance;
x2+1.0= ?
answer is quite surprising: 1.0
for x2=2.0 it calculates 1073741824
difference it is 1048576=1024*10 24
there are 1048576 distinct values. Hashing function simply calculates in
this way...


That's quite a leap of logic there...

Here's a counterexample - this class just generates random doubles and
checks whether or not the hashcode has already been seen:

using System;
using System.Collecti ons;

class Test
{
static void Main()
{
Hashtable map = new Hashtable();
Random rng = new Random();

int distinct = 0;
while (true)
{
double d = rng.Next();

int hash = d.GetHashCode() ;
if (!map.ContainsK ey(hash))
{
map[hash]=hash;
distinct++;
if (distinct % 1000==0)
{
Console.WriteLi ne (distinct);
}
}
}
}
}

It doesn't take it long to go over the number of distinct values you
claim.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6
Yunus Emre ALPÖZEN [MCAD.NET] <ye***@msakadem ik.net> wrote:
Could not understand what u mean ???
You claimed there were 1048576 distinct values returned by
Double.GetHashC ode. My program claimed that there are many more than
that - and I would strongly suspect that there are actually as many
values as there are ints, seeing as it would be easily to implement
that way.
I made several changes on your code:


Your changes show that collisions occur, which is unsurprising as I
explained in another post - there are far more doubles available than
ints! I don't see what else your version shows.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #7
Sorry, I misunderstood u. But i said that there are 1048576 distinct values
between 1.0 and 2.0
GetHashCode run as a one way function and maps a double value to another
integer value.

At last, there is no doubt; GetHashCode never returns a unique value. It
operates on value, not memory reference. I wish, GetHashCode returns a
unique value every time by using memory locations and value...
--

Thanks,
Yunus Emre ALPÖZEN
BSc, MCAD.NET

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Yunus Emre ALPÖZEN [MCAD.NET] <ye***@msakadem ik.net> wrote:
Could not understand what u mean ???
You claimed there were 1048576 distinct values returned by
Double.GetHashC ode. My program claimed that there are many more than
that - and I would strongly suspect that there are actually as many
values as there are ints, seeing as it would be easily to implement
that way.
I made several changes on your code:


Your changes show that collisions occur, which is unsurprising as I
explained in another post - there are far more doubles available than
ints! I don't see what else your version shows.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
Yunus Emre ALPÖZEN [MCAD.NET] <ye***@msakadem ik.net> wrote:
Sorry, I misunderstood u. But i said that there are 1048576 distinct values
between 1.0 and 2.0
Ah - you didn't, but I can accept that you meant to :)

Actually, again there are more distinct values than that, even between
1.0 and 2.0. The following program uses the fact that when you look at
the bit representations of doubles as a long, they're ordered:

using System;
using System.Collecti ons;

class Test
{
static void Main()
{
long d1 = BitConverter.Do ubleToInt64Bits (1.0);
long d2 = BitConverter.Do ubleToInt64Bits (2.0);

Console.WriteLi ne (d2-d1);

Hashtable map = new Hashtable();
int distinct = 0;

for (long l = d1; l <= d2; l++)
{
double d = BitConverter.In t64BitsToDouble (l);
int hash = d.GetHashCode() ;
if (!map.ContainsK ey(hash))
{
map[hash]=""; // Avoid double boxing
distinct++;
if ((distinct%1000 )==0)
{
Console.WriteLi ne (distinct);
}
}
}
}
}

The above finds over 10 million distinct hash codes on my box before it
runs out of memory.
GetHashCode run as a one way function and maps a double value to another
integer value.
Yes.
At last, there is no doubt; GetHashCode never returns a unique value.
Not for doubles, no.
It operates on value, not memory reference. I wish, GetHashCode returns a
unique value every time by using memory locations and value...


I'm glad it doesn't, otherwise it would be screwed up by the garbage
collector moving objects around in memory...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
6576
by: Avin Patel | last post by:
Hi I have question for GetHashCode() function, Is it correct in following code or there is more efficient way to implement GetHashCode() function class IntArray public int data public override int GetHashCode() int hash = 0 for (int i = 0; i < data.Length; i++
5
9605
by: Stoyan | last post by:
Hi All, I don't understand very well this part of MSDN: "Derived classes that override GetHashCode must also override Equals to guarantee that two objects considered equal have the same hash code; otherwise, Hashtable might not work correctly." Does any one know, why we must also override Equals, Please give my an example:) Thanks, Stoyan
1
2205
by: MariusI | last post by:
I have some business objects which overrides Equals to provide syntax equality instead of just reference equality. Overriding equals gives me a warning that i must override GetHashcode(). Msdn says this about implementing hashcode: (1)If two objects of the same type represent the same value, the hash function must return the same constant value for either object. (2)For the best performance, a hash function must generate a random...
5
2285
by: Metaman | last post by:
I'm trying to write a generic method to generate Hashcodes but am having some problems with (generic) collections. Here is the code of my method: public static int GetHashCode(object input) { try { Type objectType = input.GetType(); PropertyInfo properties = objectType.GetProperties();
3
1812
by: =?Utf-8?B?QWJlUg==?= | last post by:
I am trying to look for change in an instanciated object that contains a generic list<>. I first get an int value of objA.GetHashCode(). I add a few objects to the list<collection in objA I compared the initial value with the current hash code of objA and they were still the same. OK I thought maybe if I compare the internal collections I would be more successful, so I overrode the GetHashCode() method with the hashcode of the List. Still...
5
1889
by: RAM | last post by:
Hello, I would like to ask programmers such question: I have a class containing a few fields: int i; string a; bool b; int j; bool q; decimal d; I need to write GetHashCode function for this class. Could you suggest
8
5870
by: Ashish Khandelwal | last post by:
-----See below code, string str = "blair"; string strValue = "ABC"; string str1 = "brainlessness"; string strValue1 = "XYZ"; int hash = str.GetHashCode() ; // Returns 175803953 int hash1 = str1.GetHashCode(); // Returns 175803953 Hashtable ht = new Hashtable(); ht.Add(hash ,strValue); ht.Add(hash1,strValue1); // ****ERROR****
28
3789
by: Tony Johansson | last post by:
Hello! I can't figure out what point it is to use GetHashCode. I know that this GetHashCode is used for obtaining a unique integer value. Can somebody give me an example that prove the usefulness of this GetHashCode or it it of no use at all? A mean that if I get an integer from current time in some way what should I use it for?
10
1404
by: Tony | last post by:
Hello! Here I have a Card class with several methods. Now to my question I don't really fully understand what purpose this GetHashCode is used for. That's why I bring it up again. In this simple example below with the Card class what would happen if I skip this GetHashCode in this Card class? Is it possible to write some simple test program to prove that this
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9489
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10356
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10162
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9959
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8988
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7509
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4061
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.