Skip to content

Use integer division in encode_phys to prevent rounding errors with int64 #611

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions canopen/objectdictionary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,8 +484,12 @@ def decode_phys(self, value: int) -> Union[int, bool, float, str, bytes]:

def encode_phys(self, value: Union[int, bool, float, str, bytes]) -> int:
if self.data_type in INTEGER_TYPES:
value /= self.factor
value = int(round(value))
if self.factor == 1:
pass
elif isinstance(value, int) and isinstance(self.factor, int):
value = value // self.factor
else:
value = int(round(value / self.factor))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

round() already returns an integer if ndigits is omitted.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round was the original code. My contribution is only the // division, which is my use case is the right thing to do. What do you suggest?

return value

def decode_desc(self, value: int) -> str:
Expand Down