Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accessing float field gives different value than provided #515

Open
aabmass opened this issue Jan 17, 2025 · 1 comment
Open

Accessing float field gives different value than provided #515

aabmass opened this issue Jan 17, 2025 · 1 comment
Labels
priority: p2 Moderately-important priority. Fix may not be included in next release. type: bug Error or flaw in code with unintended results or allowing sub-optimal usage patterns.

Comments

@aabmass
Copy link

aabmass commented Jan 17, 2025

I had a look around but couldn't find an existing issue. There is some strange rounding with float fields when the value is accessed on an instance vs encoded:

>>> import proto
...
... class Animal(proto.Message):
...     size = proto.Field(proto.FLOAT, number=1)
...
>>> a = Animal(size=0.95)
>>> a
size: 0.95

>>> a.size
0.949999988079071

Why is a.size significantly different from the value I provided? Also the textproto produced by stringifying and the value produced by to_dict() are correct:

>>> Animal.to_dict(a)
{'size': 0.95}
>>> Animal.to_dict(a)["size"] == a.size
False

Environment details

  • Programming language: Python 3.13
  • OS: Linux
  • Language runtime version: 3.13
  • Package version: proto-plus==1.25.0

Steps to reproduce

>>> import proto
...
... class Animal(proto.Message):
...     size = proto.Field(proto.FLOAT, number=1)
...
>>> Animal(size=0.95)
size: 0.95

>>> Animal(size=0.95).size
0.949999988079071
@aabmass aabmass added priority: p2 Moderately-important priority. Fix may not be included in next release. type: bug Error or flaw in code with unintended results or allowing sub-optimal usage patterns. labels Jan 17, 2025
@aabmass aabmass changed the title Float field gives wrong value Accessing float field gives different value than provided Jan 17, 2025
@aabmass
Copy link
Author

aabmass commented Jan 17, 2025

I realized that protobuf floats are 32 bits vs python floats are 64 bits and it works correctly for proto.DOUBLE fields. Is there a way to access the "correct" value on an instance, similar to how stringifying and to_dict() do it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
priority: p2 Moderately-important priority. Fix may not be included in next release. type: bug Error or flaw in code with unintended results or allowing sub-optimal usage patterns.
Projects
None yet
Development

No branches or pull requests

1 participant