bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: REQUEST - bash floating point math support


From: Léa Gris
Subject: Re: REQUEST - bash floating point math support
Date: Sat, 15 Jun 2024 16:55:31 +0200
User-agent: Mozilla Thunderbird

On 15/06/2024 à 15:29, Koichi Murase wrote :
at which point does the conversion happens

The conversion to LC_NUMERIC format only happens during variable expansion outside of a numerical context. The numerical context can be explicit if the assigned variable has a numeric flag; it is implicit within ((numeric context))

Tgere are other numerical context in Bash, like string and array indexes, but those may retain only integer support.

So this means that the arithmetic expansions $(()) would produce a
format incompatible with the arithmetic expression. This seems
inconsistent to me, but it might be a valid option if there is no
other option.

The numerical context with a $ prefix $(()) indeed implies a string
conversion after resolving the computation within. So yes it would perform the string conversion using th LC_NUMERIC format.

An other change is that witin a declare statement or if the assigned variable has a numeric flag it is considered a numerical context.

# Numerical context of the assigned pi variable allow use of
# C format of the 3.1415 literal to be used in assignment
declare -i pi=3.1415

# give a a numeric flag
typeset -i e
# Because a has a numeric flag it accepts the dot radix delimiter within
# the assigned value
e=2.71828

# Numerical context pi / 2 computes to 1.57
# but as it is expanded into a string, it uses
# the comma radix delimiter from LC_NUMERIC=fr_FR.UTF8
str=$((pi / 2))
# Then str=1,57

# This is illegal, becahse the right-side is expanded
# to string and may not use the correct dot delimiter
declare -i arc=$(((2 * pi) / 3)

# This is a correct assignemnt
((arc = (2 * pi) / 3))

# Although arc has not been declared with a numeric flag
# it was assigned within a numerical context


I feel it is better to allow the printf implementations
to extend the conversion rather than trying to invent strange and
inconsistent behaviors among the arithmetic expressions

I agree this printf limitation is questionable.

Anyway, given the slow pace of standard evolution and to not break the standard. Having consideration for the context when manipulation values or expanding these values to a string can greatly help workaround this POSIX C restriction.

It is really a simple rule:

1. Within a numerical context, floating-point literals use the dot radix delimiter. Internally it could yse whatever fit best like IEEE 754 double precision binary64 2. Outside a numerical context, when creating a string representation of a floating-point number, the LC_NUMERIC format applies.

--
Léa Gris


reply via email to

[Prev in Thread] Current Thread [Next in Thread]