Skip to content

redo time.monotonic() to avoid double precision #343

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

Merged
merged 2 commits into from
Oct 17, 2017
Merged
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions atmel-samd/common-hal/digitalio/DigitalInOut.c
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ void common_hal_digitalio_digitalinout_switch_to_output(
pin_conf.input_pull = PORT_PIN_PULL_NONE;
port_pin_set_config(self->pin->pin, &pin_conf);

// Turn on "strong" pin driving (more current available). See DRVSTR doc in datasheet.
system_pinmux_pin_set_output_strength(self->pin->pin, SYSTEM_PINMUX_PIN_STRENGTH_HIGH);

self->output = true;
self->open_drain = drive_mode == DRIVE_MODE_OPEN_DRAIN;
common_hal_digitalio_digitalinout_set_value(self, value);
Expand Down
4 changes: 3 additions & 1 deletion shared-bindings/time/__init__.c
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@
//| :rtype: float
//|
STATIC mp_obj_t time_monotonic(void) {
return mp_obj_new_float(common_hal_time_monotonic() / 1000.0);
uint64_t time64 = common_hal_time_monotonic();
// 4294967296 = 2^32
return mp_obj_new_float(((uint32_t) (time64 >> 32) * 4294967296.0f + (uint32_t) (time64 & 0xffffffff)) / 1000.0f);
Copy link
Member

Choose a reason for hiding this comment

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

How does precision change with this? Would we get more precision by dividing by 1000.0f earlier?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I could distribute the division among the two halves, but the precision is still lost due to single-precision floating point. So I don't believe it will make a difference:

>>> (2.0**22+1)/1000 - (2.0**22+0)/1000 
0.0
>>> (2.0**22+2)/1000 - (2.0**22+1)/1000 
0.00195313
>>> (2.0**22+3)/1000 - (2.0**22+2)/1000 
0.0
>>> (2.0**22+4)/1000 - (2.0**22+3)/1000 
0.00195313
>>> 

}
MP_DEFINE_CONST_FUN_OBJ_0(time_monotonic_obj, time_monotonic);

Expand Down