Converting a unique seed string into a random, yet deterministic, float value in Ruby

前端 未结 3 1459
悲哀的现实
悲哀的现实 2020-12-18 20:44

I\'m having a hard time with this, conceptually.

Basically, I need to accept some arbitrary unique string, and be able to convert that to a normalized float value.

3条回答
  •  悲哀的现实
    2020-12-18 21:32

    The key part that you want is a way of converting a SHA1 or MD5 hash output into a float that is both deterministic and 1-1. Here's a simple solution based on md5. This could be used as integers too.

    require 'digest/md5'
    
    class String
      def float_hash
        (Digest::MD5.hexdigest(self).to_i(16)).to_f
      end
    end
    
    puts "example_string".float_hash  # returns 1.3084281619666243e+38
    

    This generates a hexadecimal hash, then converts it to an integer, then converts that to a float. Each step is deterministic.

    Note: as pointed out by @emboss, this reduces collision resistance because a double is 8 bytes and the hash is 16 bytes. It shouldn't be a big deal though by the sounds of your application.

提交回复
热议问题