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

Berry add math.round #21602

Merged
merged 4 commits into from
Jun 9, 2024
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: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ All notable changes to this project will be documented in this file.
- Matter support for Air Quality sensors (#21559)
- Matter support for bridged Air Quality (#21597)
- HASPmota rounds to nearest int values passed as 'real' (#21599)
- Berry automatic rounding of float to int when calling C mapped functions (#21601)
- Berry automatic rounding of float to int when calling C mapped functions
- Berry add `math.round`

### Breaking Changed

Expand Down
13 changes: 13 additions & 0 deletions lib/libesp32/berry/src/be_mathlib.c
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ static int m_floor(bvm *vm)
be_return(vm);
}

static int m_round(bvm *vm)
{
if (be_top(vm) >= 1 && be_isnumber(vm, 1)) {
breal x = be_toreal(vm, 1);
be_pushreal(vm, mathfunc(round)(x));
} else {
be_pushreal(vm, (breal)0.0);
}
be_return(vm);
}

static int m_sin(bvm *vm)
{
if (be_top(vm) >= 1 && be_isnumber(vm, 1)) {
Expand Down Expand Up @@ -299,6 +310,7 @@ be_native_module_attr_table(math) {
be_native_module_function("abs", m_abs),
be_native_module_function("ceil", m_ceil),
be_native_module_function("floor", m_floor),
be_native_module_function("round", m_round),
be_native_module_function("sin", m_sin),
be_native_module_function("cos", m_cos),
be_native_module_function("tan", m_tan),
Expand Down Expand Up @@ -334,6 +346,7 @@ module math (scope: global, depend: BE_USE_MATH_MODULE) {
abs, func(m_abs)
ceil, func(m_ceil)
floor, func(m_floor)
round, func(m_round)
sin, func(m_sin)
cos, func(m_cos)
tan, func(m_tan)
Expand Down
14 changes: 14 additions & 0 deletions lib/libesp32/berry/tests/math.be
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,17 @@ m_inf2 = {"v": -math.inf}
assert(json.dump(m_inf2) == '{"v":null}')
m_v = {"v": 3.5}
assert(json.dump(m_v) == '{"v":3.5}')

# math.round
assert(math.round(3) == 3)
assert(math.round(3.2) == 3)
assert(math.round(3.5) == 4)
assert(math.round(3.6) == 4)

assert(math.round(-3) == -3)
assert(math.round(-3.2) == -3)
assert(math.round(-3.5) == -4)
assert(math.round(-3.6) == -4)

assert(math.round() == 0)