protobuf icon indicating copy to clipboard operation
protobuf copied to clipboard

Ruby: Precision loss in float fields.

Open landrito opened this issue 9 years ago • 2 comments

There seems to be precision loss when packing and unpacking floating point fields. This seems to have not been caught because the test tests a passing case (as shown below).

Also double is missing an assertion.

Further discussion can be found in google-cloud-ruby/pull/1341.

require 'google/protobuf'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_message "google.test.Float" do
    optional :floating_value, :float, 1
  end
end

Float = Google::Protobuf::DescriptorPool.generated_pool.lookup("google.test.Float").msgclass

f = Float.new
f.floating_value = 0.1
p f.floating_value #=> 0.10000000149011612

f.floating_value = 0.2
p f.floating_value #=> 0.20000000298023224

f.floating_value = 0.3
p f.floating_value #=> 0.30000001192092896

f.floating_value = 0.4
p f.floating_value #=> 0.4000000059604645

f.floating_value = 0.5
p f.floating_value #=> 0.5

f.floating_value = 0.6
p f.floating_value #=> 0.6000000238418579

f.floating_value = 0.7
p f.floating_value #=> 0.699999988079071

f.floating_value = 0.8
p f.floating_value #=> 0.800000011920929

f.floating_value = 0.9
p f.floating_value #=> 0.8999999761581421

f.floating_value = 0.0
p f.floating_value #=> 0.0

landrito avatar Mar 20 '17 17:03 landrito

I don't think this is a real bug; I think we are just running into the fact that 0.1 cannot be exactly represented as a float. Representing 1/10 in base 2 is like representing 1/3 in decimal; you can never have enough digits (or bits) to get exactly the right number.

I wrote this C program to confirm this:

#include <stdio.h>

int main() {
  printf("%20.20f\n", 0.1f);
  printf("%20.20f\n", 0.1d);
  return 0;
}

Output: 0.10000000149011611938 0.10000000000000000555

acozzette avatar Mar 21 '17 14:03 acozzette

Ah good point. I'll take this as WAI. 🎉

Thanks for looking into this. Closing the issue.

landrito avatar Mar 23 '17 19:03 landrito