caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
From: Xavier Leroy <Xavier.Leroy@inria.fr>
To: caml-list@inria.fr
Subject: Re: [Caml-list] Hashing failure
Date: Fri, 21 Dec 2012 11:02:38 +0100	[thread overview]
Message-ID: <50D433BE.4010309@inria.fr> (raw)
In-Reply-To: <CAHR=Vkx3hntWcQYV8tptKnrRyKHNBdfA-6KxjfxWEp=j4Q-saQ@mail.gmail.com>

On 12/20/2012 09:18 PM, Thomas Braibant wrote:

> [Reducing a hash value to a [0, N) interval ]
> My question is : is there a safe way to bullet-proof my code against
> these pathological cases, without too much hinderance (this is some
> code whose efficiency is critical...)

Some possibilities to reduce an integer k to the interval [0, N):

  abs (k mod N)
     (if N > 0, k mod N is guaranteed to be in (-N,N) )

  (k land max_int) mod N
     ("land max_int" masks the sign bit off and preserves all other
      bits, reducing k to [0, max_int])

The latter is a bit more efficient, as it avoids the conditional in "abs".

If N is a power of 2, you can just do

  k land (N - 1)

For hash tables, it is easy to ensure that the size of the array is a
power of 2.  However, the formula above assumes that the low bits of k
have good distribution, which is not always the case if k is computed
with a simple hash function.  You can also "mix up" some of the high
bits before taking the low bits, e.g.

(k lxor (k lsr 16)) land (N - 1)

Hope this helps,

- Xavier


  parent reply	other threads:[~2012-12-21 10:02 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
     [not found] <CAHR=VkzBhR5FMsWO-_BVzYV4yhSARP8rg7G3b=jezU6OOOg0jQ@mail.gmail.com>
2012-12-20 20:18 ` Thomas Braibant
2012-12-20 20:32   ` [Caml-list] " Thomas Braibant
2012-12-20 21:01     ` Martin Jambon
2012-12-21  7:58   ` [Caml-list] " Jacques Garrigue
2012-12-21 10:02   ` Xavier Leroy [this message]
2012-12-21 19:03     ` Martin Jambon

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=50D433BE.4010309@inria.fr \
    --to=xavier.leroy@inria.fr \
    --cc=caml-list@inria.fr \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).