# Contexts for floating-point math?

**URL:** <https://discuss.python.org/t/contexts-for-floating-point-math/104388>\
**Category:** Ideas\
**Created:** [October 15, 2025, 1:20pm UTC](https://discuss.python.org/t/contexts-for-floating-point-math/104388 "2025-10-15T13:20:06Z")\
**Posts on this page:** 1\
**Showing post:** 21

<div class="post-metadata">

**Author:** ![skirpichev](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/skirpichev/32/10996_2.png) [@skirpichev](https://discuss.python.org/u/skirpichev)\
**Post date:** [October 17, 2025, 2:24am UTC](https://discuss.python.org/t/contexts-for-floating-point-math/104388/21 "2025-10-17T02:24:56Z")

</div>

> [@tstefan](#):
>
> I am not very convinced by these functions since they use global state.

Yes, with a thread-local storage. That’s true not just for rounding modes, but for FPE exceptions/status flags as well.

> [@tstefan](#):
>
> like `myfunc` in my example, get screwed up (=modified) by the global context.

I don’t see it in your example, but I think I understood you correctly. Yes, it’s expected that all code in the new context will work with same altered settings for FPE. E.g. not raise exceptions for certain cases or use some non-default rounding mode.

> [@tstefan](#):
>
> For that reason, the c++ comitee tries to get rid of `fesetround`

IIUIC, they are trying to make rounding more “local”, i.e. some per-function setting. Perhaps, it’s more close to Oscar’s proposal to have mathematical functions (like sin or add) on the context object.

> [@tstefan](#):
>
> According to that paper, also the c comitee has “no real attachment to fesetround”.

I’m not aware of any proposal to replace fset/getround() in C, though the c comitee is a strange place nowadays and did strange things for floating-point math in C.

> [@oscarbenjamin](#):
>
> Currently the functions in the math module are pure functions.

Really?

```pycon
>>> FE_TONEAREST, FE_UPWARD = 0, 0x800 # magic number might be different on your system
>>> import ctypes, math
>>> libm = ctypes.CDLL('libm.so.6')
>>> libm.fesetround.argtypes = [ctypes.c_int]
>>> libm.fesetround.restype = ctypes.c_int
>>> libm.fesetround(FE_TONEAREST)
0
>>> math.log(123)
4.812184355372417
>>> libm.fesetround(FE_UPWARD)
0
>>> math.log(123)
4.812184355372418

```

---

_[View the full topic](https://discuss.python.org/t/contexts-for-floating-point-math/104388)._
