Metadata-Version: 2.3
Name: ratio-delta
Version: 1.0.1
Summary: Add functions for variants of a common arithmetic operation
Project-URL: Homepage, https://github.com/LLyaudet/RatioDelta
Project-URL: Bug Tracker, https://github.com/LLyaudet/RatioDelta/issues
Author-email: Laurent Lyaudet <laurent.lyaudet@gmail.com>
Maintainer-email: Laurent Lyaudet <laurent.lyaudet@gmail.com>
License:                    GNU LESSER GENERAL PUBLIC LICENSE
                               Version 3, 29 June 2007
        
         Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
         Everyone is permitted to copy and distribute verbatim copies
         of this license document, but changing it is not allowed.
        
        
          This version of the GNU Lesser General Public License incorporates
        the terms and conditions of version 3 of the GNU General Public
        License, supplemented by the additional permissions listed below.
        
          0. Additional Definitions.
        
          As used herein, "this License" refers to version 3 of the GNU Lesser
        General Public License, and the "GNU GPL" refers to version 3 of the GNU
        General Public License.
        
          "The Library" refers to a covered work governed by this License,
        other than an Application or a Combined Work as defined below.
        
          An "Application" is any work that makes use of an interface provided
        by the Library, but which is not otherwise based on the Library.
        Defining a subclass of a class defined by the Library is deemed a mode
        of using an interface provided by the Library.
        
          A "Combined Work" is a work produced by combining or linking an
        Application with the Library.  The particular version of the Library
        with which the Combined Work was made is also called the "Linked
        Version".
        
          The "Minimal Corresponding Source" for a Combined Work means the
        Corresponding Source for the Combined Work, excluding any source code
        for portions of the Combined Work that, considered in isolation, are
        based on the Application, and not on the Linked Version.
        
          The "Corresponding Application Code" for a Combined Work means the
        object code and/or source code for the Application, including any data
        and utility programs needed for reproducing the Combined Work from the
        Application, but excluding the System Libraries of the Combined Work.
        
          1. Exception to Section 3 of the GNU GPL.
        
          You may convey a covered work under sections 3 and 4 of this License
        without being bound by section 3 of the GNU GPL.
        
          2. Conveying Modified Versions.
        
          If you modify a copy of the Library, and, in your modifications, a
        facility refers to a function or data to be supplied by an Application
        that uses the facility (other than as an argument passed when the
        facility is invoked), then you may convey a copy of the modified
        version:
        
           a) under this License, provided that you make a good faith effort to
           ensure that, in the event an Application does not supply the
           function or data, the facility still operates, and performs
           whatever part of its purpose remains meaningful, or
        
           b) under the GNU GPL, with none of the additional permissions of
           this License applicable to that copy.
        
          3. Object Code Incorporating Material from Library Header Files.
        
          The object code form of an Application may incorporate material from
        a header file that is part of the Library.  You may convey such object
        code under terms of your choice, provided that, if the incorporated
        material is not limited to numerical parameters, data structure
        layouts and accessors, or small macros, inline functions and templates
        (ten or fewer lines in length), you do both of the following:
        
           a) Give prominent notice with each copy of the object code that the
           Library is used in it and that the Library and its use are
           covered by this License.
        
           b) Accompany the object code with a copy of the GNU GPL and this license
           document.
        
          4. Combined Works.
        
          You may convey a Combined Work under terms of your choice that,
        taken together, effectively do not restrict modification of the
        portions of the Library contained in the Combined Work and reverse
        engineering for debugging such modifications, if you also do each of
        the following:
        
           a) Give prominent notice with each copy of the Combined Work that
           the Library is used in it and that the Library and its use are
           covered by this License.
        
           b) Accompany the Combined Work with a copy of the GNU GPL and this license
           document.
        
           c) For a Combined Work that displays copyright notices during
           execution, include the copyright notice for the Library among
           these notices, as well as a reference directing the user to the
           copies of the GNU GPL and this license document.
        
           d) Do one of the following:
        
               0) Convey the Minimal Corresponding Source under the terms of this
               License, and the Corresponding Application Code in a form
               suitable for, and under terms that permit, the user to
               recombine or relink the Application with a modified version of
               the Linked Version to produce a modified Combined Work, in the
               manner specified by section 6 of the GNU GPL for conveying
               Corresponding Source.
        
               1) Use a suitable shared library mechanism for linking with the
               Library.  A suitable mechanism is one that (a) uses at run time
               a copy of the Library already present on the user's computer
               system, and (b) will operate properly with a modified version
               of the Library that is interface-compatible with the Linked
               Version.
        
           e) Provide Installation Information, but only if you would otherwise
           be required to provide such information under section 6 of the
           GNU GPL, and only to the extent that such information is
           necessary to install and execute a modified version of the
           Combined Work produced by recombining or relinking the
           Application with a modified version of the Linked Version. (If
           you use option 4d0, the Installation Information must accompany
           the Minimal Corresponding Source and Corresponding Application
           Code. If you use option 4d1, you must provide the Installation
           Information in the manner specified by section 6 of the GNU GPL
           for conveying Corresponding Source.)
        
          5. Combined Libraries.
        
          You may place library facilities that are a work based on the
        Library side by side in a single library together with other library
        facilities that are not Applications and are not covered by this
        License, and convey such a combined library under terms of your
        choice, if you do both of the following:
        
           a) Accompany the combined library with a copy of the same work based
           on the Library, uncombined with any other library facilities,
           conveyed under the terms of this License.
        
           b) Give prominent notice with the combined library that part of it
           is a work based on the Library, and explaining where to find the
           accompanying uncombined form of the same work.
        
          6. Revised Versions of the GNU Lesser General Public License.
        
          The Free Software Foundation may publish revised and/or new versions
        of the GNU Lesser General Public License from time to time. Such new
        versions will be similar in spirit to the present version, but may
        differ in detail to address new problems or concerns.
        
          Each version is given a distinguishing version number. If the
        Library as you received it specifies that a certain numbered version
        of the GNU Lesser General Public License "or any later version"
        applies to it, you have the option of following the terms and
        conditions either of that published version or of any later version
        published by the Free Software Foundation. If the Library as you
        received it does not specify a version number of the GNU Lesser
        General Public License, you may choose any version of the GNU Lesser
        General Public License ever published by the Free Software Foundation.
        
          If the Library as you received it specifies that a proxy can decide
        whether future versions of the GNU Lesser General Public License shall
        apply, that proxy's public statement of acceptance of any version is
        permanent authorization for you to choose that version for the
        Library.
License-File: COPYING
License-File: COPYING.LESSER
Keywords: Python,fused-divide-add,fused-divide-decrement,fused-divide-increment,fused-divide-subract,ratio-alpha,ratio-delta,ratio-iota,ratio-sigma
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.5
Provides-Extra: dev
Requires-Dist: black; extra == 'dev'
Requires-Dist: isort; extra == 'dev'
Requires-Dist: mypy; extra == 'dev'
Requires-Dist: pylint; extra == 'dev'
Description-Content-Type: text/markdown

# RatioDelta

[![PyPI-version-badge]][PyPI-package-page]
[![Downloads-badge]][PyPIStats-package-page]
[![Code-style:black:badge]][Black-GitHub.com]
[![Imports:isort:badge]][Isort-GitHub.io]
[![Typecheck:mypy:badge]][Typecheck-mypy-lang.org]
[![Linting:pylint:badge]][Pylint-GitHub.com]
[![CodeFactor-badge]][CodeFactor-package-page]
[![CodeClimateMaintainability-badge]][CodeClimateM13y-package-page]
[![Codacy-badge]][Codacy-package-page]
![GitHub-top-language-badge]
![GitHub-license-badge]
![PyPI-python-version-badge]
![GitHub-code-size-in-bytes-badge]

|     **An unknown? but somewhat common arithmetic operation**     |

In accounting, it is common to compute (a/b - 1),
or (a/b - 1) * 100 if you want percents.
Following Knuth's advice "Name and conquer",
we give the name ratio-delta to the binary operation a/b - 1.
We do know that Knuth can safely apply his advice,
whilst for mere mortals the answer is mostly
"Don't piss me off with your fancy name." ;)

If you think relative error, fused divide-add,
or fused divide-subtract, you're right but read-on :)

Here is a potential implementation with error handling
for PostgreSQL:
```sql
CREATE FUNCTION ratio_delta(
  a double precision,
  b double precision,
  both_null double precision DEFAULT NULL,
  a_null double precision DEFAULT NULL,
  b_null double precision DEFAULT NULL,
  b_zero double precision DEFAULT NULL
) RETURNS double precision AS $$
    SELECT CASE
      WHEN a IS NULL AND b IS NULL THEN both_null
      WHEN a IS NULL THEN a_null
      WHEN b IS NULL THEN b_null
      WHEN b = 0 THEN b_zero
      ELSE a/b - 1
    END
$$ LANGUAGE SQL;

-- Test it
SELECT ratio_delta(1, 2);
SELECT ratio_delta(NULL, NULL, -100, -101, -102, -103);
SELECT ratio_delta(NULL, 2, -100, -101, -102, -103);
SELECT ratio_delta(1, NULL, -100, -101, -102, -103);
SELECT ratio_delta(1, 0, -100, -101, -102, -103);
```

## What is it good for?

If accounting department wants to compare the invoiced total
of a supplier order compared to the expected price of
what you ordered to your supplier,
they may ask you a report with all supplier orders where ratio-delta
of invoiced total and expected total is more than 5 percent.
First of by having a name, you can communicate efficiently
and precisely with the accounting department,
instead of:

- "The ratio is more than 5 percents"
  which has clearly a different meaning
  (so you want any supplier order where the invoice is at least
  one twentieth of expected price? really?),
- "The difference is more than 5 percents"
  which has clearly another different meaning
  (so you want any supplier order where the invoice is at least
  5 cents above the expected price? really?).

Secondly, your SQL is readable and simple:
```sql
SELECT * FROM supplier_order
WHERE ratio_delta(
  supplier_order.invoiced_total,
  supplier_order.expected_total,
  0, 0, 0, 0
) > 0.05;
```

Make sure to have a look at the issues on GitHub!

## Variants

The word we propose can easily be combined with the following:

- absolute ratio-delta: abs(a/b - 1)
- ratio-delta percent: (a/b - 1) * 100
- absolute ratio-delta percent: abs(a/b - 1) * 100

Moreover, you can add rounding.
You can obtain a synthetic function with (too) many arguments like:
```sql
CREATE FUNCTION ratio_delta(
  a double precision,
  b double precision,
  is_absolute boolean DEFAULT FALSE,
  is_percent boolean DEFAULT FALSE,
  round_to smallint DEFAULT NULL,
  both_null double precision DEFAULT NULL,
  a_null double precision DEFAULT NULL,
  b_null double precision DEFAULT NULL,
  b_zero double precision DEFAULT NULL
) RETURNS double precision AS $$
    SELECT CASE
      WHEN a IS NULL and b IS NULL THEN both_null
      WHEN a IS NULL THEN a_null
      WHEN b IS NULL THEN b_null
      WHEN b = 0 THEN b_zero
      WHEN is_absolute
       AND is_percent
       AND round_to IS NOT NULL
       THEN round(abs(a/b - 1) * 100, round_to)
      WHEN is_absolute AND is_percent THEN abs(a/b - 1) * 100
      WHEN is_absolute AND round_to IS NOT NULL
       THEN round(abs(a/b - 1), round_to)
      WHEN is_percent AND round_to IS NOT NULL
       THEN round((a/b - 1) * 100, round_to)
      WHEN is_absolute THEN abs(a/b - 1)
      WHEN is_percent THEN (a/b - 1) * 100
      WHEN round_to IS NOT NULL THEN round(a/b - 1, round_to)
      ELSE a/b - 1
    END
$$ LANGUAGE SQL;
```
It will factorize your code and be completely "flexible".
But I do not know a way to specialize
and inline it to be efficient in SQL.
You can still do, for example:
```sql
CREATE FUNCTION absolute_rounded_ratio_delta(
  a double precision,
  b double precision,
  round_to smallint DEFAULT NULL,
) RETURNS double precision AS $$
    SELECT ratio_delta(a, b, TRUE, FALSE, round_to, 0, 0, 0, 0)
$$ LANGUAGE SQL;
```

The "full-feature" function can be slightly optimized (less branching)
and generalized with a "scale" argument instead of "is_percent":
```sql
CREATE FUNCTION ratio_delta(
  a double precision,
  b double precision,
  is_absolute boolean DEFAULT FALSE,
  scale double precision DEFAULT 1,
  round_to smallint DEFAULT NULL,
  both_null double precision DEFAULT NULL,
  a_null double precision DEFAULT NULL,
  b_null double precision DEFAULT NULL,
  b_zero double precision DEFAULT NULL
) RETURNS double precision AS $$
    SELECT CASE
      WHEN a IS NULL and b IS NULL THEN both_null
      WHEN a IS NULL THEN a_null
      WHEN b IS NULL THEN b_null
      WHEN b = 0 THEN b_zero
      WHEN is_absolute AND round_to IS NOT NULL
       THEN round(abs(a/b - 1) * scale, round_to)
      WHEN is_absolute THEN abs(a/b - 1) * scale
      WHEN round_to IS NOT NULL
       THEN round((a/b - 1) * scale, round_to)
      ELSE (a/b - 1) * scale
    END
$$ LANGUAGE SQL;
```
But again, it would be nice if the SQL interpreter knows to drop
the multiplication if scale is the constant 1.

## Relative error

Ratio-delta is closely related to relative error
which is most of the time "absolute ratio-delta":
abs(a/b - 1) = abs((a-b)/b),
where a is the approximation and b is the exact value:
<https://en.wikipedia.org/wiki/Approximation_error>.
Sometimes the term (signed) relative error denotes the ratio-delta:
<https://mathworld.wolfram.com/RelativeError.html>.
But the term absolute relative error would be ambiguous
with absolute error abs(a-b).
Moreover the term relative error is not neutral
and is domain specific (error analysis domain),
instead of denoting what is done.

```sql
CREATE FUNCTION absolute_rounded_ratio_delta(
  a double precision,
  b double precision,
  round_to smallint DEFAULT NULL,
) RETURNS double precision AS $$
    SELECT ratio_delta(a, b, TRUE, 1, round_to, 0, 0, 0, 0)
$$ LANGUAGE SQL;
```

is the same as:

```sql
CREATE FUNCTION rounded_relative_error(
  a double precision,
  b double precision,
  round_to smallint DEFAULT NULL,
) RETURNS double precision AS $$
    SELECT ratio_delta(a, b, TRUE, 1, round_to, 0, 0, 0, 0)
$$ LANGUAGE SQL;
```

This detour from accounting to relative error via a new name
was the opportunity to give you SQL functions for it,
and see that no major database has a function
for (signed) relative error:

- <https://www.postgresql.org/docs/current/functions-math.html>
- <https://mariadb.com/kb/en/numeric-functions/>
- <https://dev.mysql.com/doc/refman/8.0/en/numeric-functions.html>
- <https://docs.oracle.com/cd/E49933_01/server.770/es_eql/src/ceql_functions_numeric.html>
- <https://learn.microsoft.com/en-us/sql/odbc/reference/appendixes/numeric-functions?view=sql-server-ver16>

There also does not seem to have any CPU architecture
that has instructions for (signed) relative error.

We use relative error by hand
to analyze the properties of floating-point numbers,
but there is no shortcut to analyze relative errors
in significant hardware and software.

The fact is that error handling made it useful for us
to define such functions in SQL.
It would probably be a good thing
that it is available for more software parts like databases.
And even maybe it would yield significant optimization with hardware.

## Other uses

I asked a friend of mine if he saw any use in physics.
He told me:
"Not later than last week, I was using it with variable offset
for a Laser Doppler vibrometer
<https://en.wikipedia.org/wiki/Laser_Doppler_vibrometer>.
For each frequency f, I had to compute:

Normalized displacement corrected for each frequency
 = Measured displacement / applied tension - measure offset

<=> |H(f)| = abs(D(f) / U(f) - Offset (f))

It is frequent for measuring devices:

H = (A / B - O)*G

Default Offset O=1

Default gain G=100
"

"
Another more frequent example is in impedancemetry,

Z(f) = U(f) / I(f)

but, in practice, you must calibrate your device

Z_corrected := U_measured / I_measured - Z_calibration
"

Let's continue to name and conquer, and call:

- ratio-offset
  when an offset is applied positively or negatively to a ratio,
- ratio-iota when a unit offset is added a/b + 1 (iota as increment),
- ratio-alpha when a variable offset is added
  (alpha as add, it is a ternary operation a/b + c),
- ratio-delta when a unit offset is subtracted
  (delta as decrement, I have been lucky with my initial choice),
- ratio-sigma when a variable offset is subtracted
  (sigma as subtract, it is a ternary operation a/b - c),
- absolute... when we take the absolute value,
- rounded... when we round the result,
- scaled... when a scale/gain is applied.

Just in case, if someone does not know or if it hurts someone:

- "add a to b" corresponds to "a + b",
- "increment a by b" corresponds to "a := a + b".

Hence, yes I'm slightly abusing semantics
since most increments in source code happen to be increments by 1.
And it is handy to distinguish between "a + b" and "a + 1"
(or between "a := a + b" and "a := a + 1"),
by using "increment" when the second operand is 1
and "add" when the second operand is variable.
I'm not the first to use this trick,
and will probably not be the last ;).

For hardware, the topic of ratio-alpha and ratio-sigma
has been addressed in academic papers on fused divide-add:

- <https://ieeexplore.ieee.org/abstract/document/5451057>
- <https://ieeexplore.ieee.org/document/5349981>
- <https://ieeexplore.ieee.org/abstract/document/7280029>

It was already envisionned in 1994:

- <https://www.researchgate.net/profile/Michael-Flynn-7/publication/3043776_Design_issues_in_division_and_other_floating-point_operations/links/5467be1a0cf2f5eb18036e1e/Design-issues-in-division-and-other-floating-point-operations.pdf>

But we could not check if someone linked explicitely
relative error with fused divide-add.
(A paper about fused divide-add/subtract can talk about relative error
as a tool to analyze the fused divide-add/subtract method,
without noting that the relative error can be computed
by a fused divide-subtract
and we do not have access to most of full-texts on the subject.)

But it does not seem to be in current Instruction Set Architectures:

- <https://cdrdv2.intel.com/v1/dl/getContent/671110>
- <https://developer.arm.com/documentation/ddi0602/2023-03/SIMD-FP-Instructions?lang=en>

With dedicated function in software,
it may be easier to use dedicated hardware if it exists one day.

## Voltage divider, and beyond?

If we look at ratio-iota (a/b) + 1,
when you have a voltage divider
(<https://en.wikipedia.org/wiki/Voltage_divider>)
with two resistors,
the coefficient applied to tension is (Z2/(Z1+Z2)) = 1 / (Z1/Z2 + 1).
Thus, we could, but probably should not, add:

- inverted... when you take the inverse of it.

And the coefficient in a voltage divider
is inverted ratio-iota, for example.
But it is clearly not the most efficient way to compute it.
And if we look at the variable offset versions of it:

- inverted ratio-alpha: 1/(a/b + c) = 1/((a + bc)/b) = b/(a + bc),
- inverted ratio-sigma: 1/(a/b - c) = 1/((a - bc)/b) = b/(a - bc),

we can see the fused multiply-add a + bc = bc + a,
but we cannot see the fused multiply-subtract a - bc != bc - a
<https://www.ibm.com/docs/en/aix/7.1?topic=set-fmsub-fms-floating-multiply-subtract-instruction>.
We do not know if there may be uses
for fused multiply-subtract of type 2 a - bc
on top of fused multiply-subtract of type 1 bc - a.

Other uses of ratio-iota appears
with differential and operational amplifiers,
see
<https://www.electronique-et-informatique.fr/anglais/Amplificateur_differentiel.php>
for example.

## Source code

The source code is available for many languages.
It is quite verbose and repetitive because we wanted to explicit
what could be assembly operation in our point of view.

[PyPI-python-version-badge]: https://img.shields.io/pypi/pyversions/ratio-delta

[PyPI-version-badge]: https://img.shields.io/pypi/v/ratio-delta.svg

[PyPI-package-page]: https://pypi.org/project/ratio-delta/

[Downloads-badge]: https://img.shields.io/pypi/dm/ratio-delta

[PyPIStats-package-page]: https://pypistats.org/packages/ratio-delta

[Code-style:black:badge]: https://img.shields.io/badge/code%20style-black-000000.svg

[Black-GitHub.com]: https://github.com/psf/black

[Imports:isort:badge]: https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336

[Isort-GitHub.io]: https://pycqa.github.io/isort/

[Typecheck:mypy:badge]: https://www.mypy-lang.org/static/mypy_badge.svg

[Typecheck-mypy-lang.org]: https://mypy-lang.org/

[Linting:pylint:badge]: https://img.shields.io/badge/linting-pylint-yellowgreen

[Pylint-GitHub.com]: https://github.com/pylint-dev/pylint

[CodeFactor-badge]: https://www.codefactor.io/repository/github/llyaudet/RatioDelta/badge/main

[CodeFactor-package-page]: https://www.codefactor.io/repository/github/llyaudet/RatioDelta/overview/main

[CodeClimateMaintainability-badge]: https://api.codeclimate.com/v1/badges/23218bfc6b7b7dd5c2aa/maintainability

[CodeClimateM13y-package-page]: https://codeclimate.com/github/LLyaudet/RatioDelta/maintainability

[Codacy-badge]: https://app.codacy.com/project/badge/Grade/d4c03e8e52194c1fb3fb51bb58c4f54c

[Codacy-package-page]: https://app.codacy.com/gh/LLyaudet/RatioDelta/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade

[GitHub-top-language-badge]: https://img.shields.io/github/languages/top/llyaudet/RatioDelta

[GitHub-license-badge]: https://img.shields.io/github/license/llyaudet/RatioDelta

[GitHub-code-size-in-bytes-badge]: https://img.shields.io/github/languages/code-size/llyaudet/RatioDelta
