ratio-delta


Nameratio-delta JSON
Version 1.0.2 PyPI version JSON
download
home_pageNone
SummaryAdd functions for variants of a common arithmetic operation
upload_time2024-05-03 02:53:27
maintainerNone
docs_urlNone
authorNone
requires_python>=3.5
licenseGNU 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.
keywords python fused-divide-add fused-divide-decrement fused-divide-increment fused-divide-subract ratio-alpha ratio-delta ratio-iota ratio-sigma
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "ratio-delta",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.5",
    "maintainer_email": "Laurent Lyaudet <laurent.lyaudet@gmail.com>",
    "keywords": "Python, fused-divide-add, fused-divide-decrement, fused-divide-increment, fused-divide-subract, ratio-alpha, ratio-delta, ratio-iota, ratio-sigma",
    "author": null,
    "author_email": "Laurent Lyaudet <laurent.lyaudet@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/e0/22/7aba72a60388b18dcd64666d78bad41e7e51fb668df1f27b6ab7e463dbe7/ratio_delta-1.0.2.tar.gz",
    "platform": null,
    "description": "# RatioDelta\n\n[![PyPI-version-badge]][PyPI-package-page]\n[![Downloads-badge]][PyPIStats-package-page]\n[![Code-style:black:badge]][Black-GitHub.com]\n[![Imports:isort:badge]][Isort-GitHub.io]\n[![Typecheck:mypy:badge]][Typecheck-mypy-lang.org]\n[![Linting:pylint:badge]][Pylint-GitHub.com]\n[![CodeFactor-badge]][CodeFactor-package-page]\n[![CodeClimateMaintainability-badge]][CodeClimateM13y-package-page]\n[![Codacy-badge]][Codacy-package-page]\n![GitHub-top-language-badge]\n![GitHub-license-badge]\n![PyPI-python-version-badge]\n![GitHub-code-size-in-bytes-badge]\n\n|     **An unknown? but somewhat common arithmetic operation**     |\n\nIn accounting, it is common to compute (a/b - 1),\nor (a/b - 1) * 100 if you want percents.\nFollowing Knuth's advice \"Name and conquer\",\nwe give the name ratio-delta to the binary operation a/b - 1.\nWe do know that Knuth can safely apply his advice,\nwhilst for mere mortals the answer is mostly\n\"Don't piss me off with your fancy name.\" ;)\n\nIf you think relative error, fused divide-add,\nor fused divide-subtract, you're right but read-on :)\n\nHere is a potential implementation with error handling\nfor PostgreSQL:\n```sql\nCREATE FUNCTION ratio_delta(\n  a double precision,\n  b double precision,\n  both_null double precision DEFAULT NULL,\n  a_null double precision DEFAULT NULL,\n  b_null double precision DEFAULT NULL,\n  b_zero double precision DEFAULT NULL\n) RETURNS double precision AS $$\n    SELECT CASE\n      WHEN a IS NULL AND b IS NULL THEN both_null\n      WHEN a IS NULL THEN a_null\n      WHEN b IS NULL THEN b_null\n      WHEN b = 0 THEN b_zero\n      ELSE a/b - 1\n    END\n$$ LANGUAGE SQL;\n\n-- Test it\nSELECT ratio_delta(1, 2);\nSELECT ratio_delta(NULL, NULL, -100, -101, -102, -103);\nSELECT ratio_delta(NULL, 2, -100, -101, -102, -103);\nSELECT ratio_delta(1, NULL, -100, -101, -102, -103);\nSELECT ratio_delta(1, 0, -100, -101, -102, -103);\n```\n\n## What is it good for?\n\nIf accounting department wants to compare the invoiced total\nof a supplier order compared to the expected price of\nwhat you ordered to your supplier,\nthey may ask you a report with all supplier orders where ratio-delta\nof invoiced total and expected total is more than 5 percent.\nFirst of by having a name, you can communicate efficiently\nand precisely with the accounting department,\ninstead of:\n\n- \"The ratio is more than 5 percents\"\n  which has clearly a different meaning\n  (so you want any supplier order where the invoice is at least\n  one twentieth of expected price? really?),\n- \"The difference is more than 5 percents\"\n  which has clearly another different meaning\n  (so you want any supplier order where the invoice is at least\n  5 cents above the expected price? really?).\n\nSecondly, your SQL is readable and simple:\n```sql\nSELECT * FROM supplier_order\nWHERE ratio_delta(\n  supplier_order.invoiced_total,\n  supplier_order.expected_total,\n  0, 0, 0, 0\n) > 0.05;\n```\n\nMake sure to have a look at the issues on GitHub!\n\n## Variants\n\nThe word we propose can easily be combined with the following:\n\n- absolute ratio-delta: abs(a/b - 1)\n- ratio-delta percent: (a/b - 1) * 100\n- absolute ratio-delta percent: abs(a/b - 1) * 100\n\nMoreover, you can add rounding.\nYou can obtain a synthetic function with (too) many arguments like:\n```sql\nCREATE FUNCTION ratio_delta(\n  a double precision,\n  b double precision,\n  is_absolute boolean DEFAULT FALSE,\n  is_percent boolean DEFAULT FALSE,\n  round_to smallint DEFAULT NULL,\n  both_null double precision DEFAULT NULL,\n  a_null double precision DEFAULT NULL,\n  b_null double precision DEFAULT NULL,\n  b_zero double precision DEFAULT NULL\n) RETURNS double precision AS $$\n    SELECT CASE\n      WHEN a IS NULL and b IS NULL THEN both_null\n      WHEN a IS NULL THEN a_null\n      WHEN b IS NULL THEN b_null\n      WHEN b = 0 THEN b_zero\n      WHEN is_absolute\n       AND is_percent\n       AND round_to IS NOT NULL\n       THEN round(abs(a/b - 1) * 100, round_to)\n      WHEN is_absolute AND is_percent THEN abs(a/b - 1) * 100\n      WHEN is_absolute AND round_to IS NOT NULL\n       THEN round(abs(a/b - 1), round_to)\n      WHEN is_percent AND round_to IS NOT NULL\n       THEN round((a/b - 1) * 100, round_to)\n      WHEN is_absolute THEN abs(a/b - 1)\n      WHEN is_percent THEN (a/b - 1) * 100\n      WHEN round_to IS NOT NULL THEN round(a/b - 1, round_to)\n      ELSE a/b - 1\n    END\n$$ LANGUAGE SQL;\n```\nIt will factorize your code and be completely \"flexible\".\nBut I do not know a way to specialize\nand inline it to be efficient in SQL.\nYou can still do, for example:\n```sql\nCREATE FUNCTION absolute_rounded_ratio_delta(\n  a double precision,\n  b double precision,\n  round_to smallint DEFAULT NULL,\n) RETURNS double precision AS $$\n    SELECT ratio_delta(a, b, TRUE, FALSE, round_to, 0, 0, 0, 0)\n$$ LANGUAGE SQL;\n```\n\nThe \"full-feature\" function can be slightly optimized (less branching)\nand generalized with a \"scale\" argument instead of \"is_percent\":\n```sql\nCREATE FUNCTION ratio_delta(\n  a double precision,\n  b double precision,\n  is_absolute boolean DEFAULT FALSE,\n  scale double precision DEFAULT 1,\n  round_to smallint DEFAULT NULL,\n  both_null double precision DEFAULT NULL,\n  a_null double precision DEFAULT NULL,\n  b_null double precision DEFAULT NULL,\n  b_zero double precision DEFAULT NULL\n) RETURNS double precision AS $$\n    SELECT CASE\n      WHEN a IS NULL and b IS NULL THEN both_null\n      WHEN a IS NULL THEN a_null\n      WHEN b IS NULL THEN b_null\n      WHEN b = 0 THEN b_zero\n      WHEN is_absolute AND round_to IS NOT NULL\n       THEN round(abs(a/b - 1) * scale, round_to)\n      WHEN is_absolute THEN abs(a/b - 1) * scale\n      WHEN round_to IS NOT NULL\n       THEN round((a/b - 1) * scale, round_to)\n      ELSE (a/b - 1) * scale\n    END\n$$ LANGUAGE SQL;\n```\nBut again, it would be nice if the SQL interpreter knows to drop\nthe multiplication if scale is the constant 1.\n\n## Relative error\n\nRatio-delta is closely related to relative error\nwhich is most of the time \"absolute ratio-delta\":\nabs(a/b - 1) = abs((a-b)/b),\nwhere a is the approximation and b is the exact value:\n<https://en.wikipedia.org/wiki/Approximation_error>.\nSometimes the term (signed) relative error denotes the ratio-delta:\n<https://mathworld.wolfram.com/RelativeError.html>.\nBut the term absolute relative error would be ambiguous\nwith absolute error abs(a-b).\nMoreover the term relative error is not neutral\nand is domain specific (error analysis domain),\ninstead of denoting what is done.\n\n```sql\nCREATE FUNCTION absolute_rounded_ratio_delta(\n  a double precision,\n  b double precision,\n  round_to smallint DEFAULT NULL,\n) RETURNS double precision AS $$\n    SELECT ratio_delta(a, b, TRUE, 1, round_to, 0, 0, 0, 0)\n$$ LANGUAGE SQL;\n```\n\nis the same as:\n\n```sql\nCREATE FUNCTION rounded_relative_error(\n  a double precision,\n  b double precision,\n  round_to smallint DEFAULT NULL,\n) RETURNS double precision AS $$\n    SELECT ratio_delta(a, b, TRUE, 1, round_to, 0, 0, 0, 0)\n$$ LANGUAGE SQL;\n```\n\nThis detour from accounting to relative error via a new name\nwas the opportunity to give you SQL functions for it,\nand see that no major database has a function\nfor (signed) relative error:\n\n- <https://www.postgresql.org/docs/current/functions-math.html>\n- <https://mariadb.com/kb/en/numeric-functions/>\n- <https://dev.mysql.com/doc/refman/8.0/en/numeric-functions.html>\n- <https://docs.oracle.com/cd/E49933_01/server.770/es_eql/src/ceql_functions_numeric.html>\n- <https://learn.microsoft.com/en-us/sql/odbc/reference/appendixes/numeric-functions?view=sql-server-ver16>\n\nThere also does not seem to have any CPU architecture\nthat has instructions for (signed) relative error.\n\nWe use relative error by hand\nto analyze the properties of floating-point numbers,\nbut there is no shortcut to analyze relative errors\nin significant hardware and software.\n\nThe fact is that error handling made it useful for us\nto define such functions in SQL.\nIt would probably be a good thing\nthat it is available for more software parts like databases.\nAnd even maybe it would yield significant optimization with hardware.\n\n## Other uses\n\nI asked a friend of mine if he saw any use in physics.\nHe told me:\n\"Not later than last week, I was using it with variable offset\nfor a Laser Doppler vibrometer\n<https://en.wikipedia.org/wiki/Laser_Doppler_vibrometer>.\nFor each frequency f, I had to compute:\n\nNormalized displacement corrected for each frequency\n = Measured displacement / applied tension - measure offset\n\n<=> |H(f)| = abs(D(f) / U(f) - Offset (f))\n\nIt is frequent for measuring devices:\n\nH = (A / B - O)*G\n\nDefault Offset O=1\n\nDefault gain G=100\n\"\n\n\"\nAnother more frequent example is in impedancemetry,\n\nZ(f) = U(f) / I(f)\n\nbut, in practice, you must calibrate your device\n\nZ_corrected := U_measured / I_measured - Z_calibration\n\"\n\nLet's continue to name and conquer, and call:\n\n- ratio-offset\n  when an offset is applied positively or negatively to a ratio,\n- ratio-iota when a unit offset is added a/b + 1 (iota as increment),\n- ratio-alpha when a variable offset is added\n  (alpha as add, it is a ternary operation a/b + c),\n- ratio-delta when a unit offset is subtracted\n  (delta as decrement, I have been lucky with my initial choice),\n- ratio-sigma when a variable offset is subtracted\n  (sigma as subtract, it is a ternary operation a/b - c),\n- absolute... when we take the absolute value,\n- rounded... when we round the result,\n- scaled... when a scale/gain is applied.\n\nJust in case, if someone does not know or if it hurts someone:\n\n- \"add a to b\" corresponds to \"a + b\",\n- \"increment a by b\" corresponds to \"a := a + b\".\n\nHence, yes I'm slightly abusing semantics\nsince most increments in source code happen to be increments by 1.\nAnd it is handy to distinguish between \"a + b\" and \"a + 1\"\n(or between \"a := a + b\" and \"a := a + 1\"),\nby using \"increment\" when the second operand is 1\nand \"add\" when the second operand is variable.\nI'm not the first to use this trick,\nand will probably not be the last ;).\n\nFor hardware, the topic of ratio-alpha and ratio-sigma\nhas been addressed in academic papers on fused divide-add:\n\n- <https://ieeexplore.ieee.org/abstract/document/5451057>\n- <https://ieeexplore.ieee.org/document/5349981>\n- <https://ieeexplore.ieee.org/abstract/document/7280029>\n\nIt was already envisionned in 1994:\n\n- <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>\n\nBut we could not check if someone linked explicitely\nrelative error with fused divide-add.\n(A paper about fused divide-add/subtract can talk about relative error\nas a tool to analyze the fused divide-add/subtract method,\nwithout noting that the relative error can be computed\nby a fused divide-subtract\nand we do not have access to most of full-texts on the subject.)\n\nBut it does not seem to be in current Instruction Set Architectures:\n\n- <https://cdrdv2.intel.com/v1/dl/getContent/671110>\n- <https://developer.arm.com/documentation/ddi0602/2023-03/SIMD-FP-Instructions?lang=en>\n\nWith dedicated function in software,\nit may be easier to use dedicated hardware if it exists one day.\n\n## Voltage divider, and beyond?\n\nIf we look at ratio-iota (a/b) + 1,\nwhen you have a voltage divider\n(<https://en.wikipedia.org/wiki/Voltage_divider>)\nwith two resistors,\nthe coefficient applied to tension is (Z2/(Z1+Z2)) = 1 / (Z1/Z2 + 1).\nThus, we could, but probably should not, add:\n\n- inverted... when you take the inverse of it.\n\nAnd the coefficient in a voltage divider\nis inverted ratio-iota, for example.\nBut it is clearly not the most efficient way to compute it.\nAnd if we look at the variable offset versions of it:\n\n- inverted ratio-alpha: 1/(a/b + c) = 1/((a + bc)/b) = b/(a + bc),\n- inverted ratio-sigma: 1/(a/b - c) = 1/((a - bc)/b) = b/(a - bc),\n\nwe can see the fused multiply-add a + bc = bc + a,\nbut we cannot see the fused multiply-subtract a - bc != bc - a\n<https://www.ibm.com/docs/en/aix/7.1?topic=set-fmsub-fms-floating-multiply-subtract-instruction>.\nWe do not know if there may be uses\nfor fused multiply-subtract of type 2 a - bc\non top of fused multiply-subtract of type 1 bc - a.\n\nOther uses of ratio-iota appears\nwith differential and operational amplifiers,\nsee\n<https://www.electronique-et-informatique.fr/anglais/Amplificateur_differentiel.php>\nfor example.\n\n## Source code\n\nThe source code is available for many languages.\nIt is quite verbose and repetitive because we wanted to explicit\nwhat could be assembly operation in our point of view.\n\n[PyPI-python-version-badge]: https://img.shields.io/pypi/pyversions/ratio-delta\n\n[PyPI-version-badge]: https://img.shields.io/pypi/v/ratio-delta.svg\n\n[PyPI-package-page]: https://pypi.org/project/ratio-delta/\n\n[Downloads-badge]: https://img.shields.io/pypi/dm/ratio-delta\n\n[PyPIStats-package-page]: https://pypistats.org/packages/ratio-delta\n\n[Code-style:black:badge]: https://img.shields.io/badge/code%20style-black-000000.svg\n\n[Black-GitHub.com]: https://github.com/psf/black\n\n[Imports:isort:badge]: https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336\n\n[Isort-GitHub.io]: https://pycqa.github.io/isort/\n\n[Typecheck:mypy:badge]: https://www.mypy-lang.org/static/mypy_badge.svg\n\n[Typecheck-mypy-lang.org]: https://mypy-lang.org/\n\n[Linting:pylint:badge]: https://img.shields.io/badge/linting-pylint-yellowgreen\n\n[Pylint-GitHub.com]: https://github.com/pylint-dev/pylint\n\n[CodeFactor-badge]: https://www.codefactor.io/repository/github/llyaudet/RatioDelta/badge/main\n\n[CodeFactor-package-page]: https://www.codefactor.io/repository/github/llyaudet/RatioDelta/overview/main\n\n[CodeClimateMaintainability-badge]: https://api.codeclimate.com/v1/badges/23218bfc6b7b7dd5c2aa/maintainability\n\n[CodeClimateM13y-package-page]: https://codeclimate.com/github/LLyaudet/RatioDelta/maintainability\n\n[Codacy-badge]: https://app.codacy.com/project/badge/Grade/d4c03e8e52194c1fb3fb51bb58c4f54c\n\n[Codacy-package-page]: https://app.codacy.com/gh/LLyaudet/RatioDelta/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade\n\n[GitHub-top-language-badge]: https://img.shields.io/github/languages/top/llyaudet/RatioDelta\n\n[GitHub-license-badge]: https://img.shields.io/github/license/llyaudet/RatioDelta\n\n[GitHub-code-size-in-bytes-badge]: https://img.shields.io/github/languages/code-size/llyaudet/RatioDelta\n",
    "bugtrack_url": null,
    "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.",
    "summary": "Add functions for variants of a common arithmetic operation",
    "version": "1.0.2",
    "project_urls": {
        "Bug Tracker": "https://github.com/LLyaudet/RatioDelta/issues",
        "Homepage": "https://github.com/LLyaudet/RatioDelta"
    },
    "split_keywords": [
        "python",
        " fused-divide-add",
        " fused-divide-decrement",
        " fused-divide-increment",
        " fused-divide-subract",
        " ratio-alpha",
        " ratio-delta",
        " ratio-iota",
        " ratio-sigma"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8de5d2564bcb8d19b146a11be92860dd66ae67ca49b4028e99f3f38f1d49269a",
                "md5": "799056f35ae7656c3cc6f849559188e1",
                "sha256": "c7e7657fe2b7e8abb63166d6977e1d7998e73c0e5d1072d231231e71d05eda36"
            },
            "downloads": -1,
            "filename": "ratio_delta-1.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "799056f35ae7656c3cc6f849559188e1",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.5",
            "size": 25156,
            "upload_time": "2024-05-03T02:53:25",
            "upload_time_iso_8601": "2024-05-03T02:53:25.258637Z",
            "url": "https://files.pythonhosted.org/packages/8d/e5/d2564bcb8d19b146a11be92860dd66ae67ca49b4028e99f3f38f1d49269a/ratio_delta-1.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e0227aba72a60388b18dcd64666d78bad41e7e51fb668df1f27b6ab7e463dbe7",
                "md5": "cc4b65d348ca0cb4f4d1cd556827bf87",
                "sha256": "1d336ac9aa504e997bdfc947b7229a4d60546d6efeeb67e279d367fb736be5f2"
            },
            "downloads": -1,
            "filename": "ratio_delta-1.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "cc4b65d348ca0cb4f4d1cd556827bf87",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.5",
            "size": 26698,
            "upload_time": "2024-05-03T02:53:27",
            "upload_time_iso_8601": "2024-05-03T02:53:27.939971Z",
            "url": "https://files.pythonhosted.org/packages/e0/22/7aba72a60388b18dcd64666d78bad41e7e51fb668df1f27b6ab7e463dbe7/ratio_delta-1.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-03 02:53:27",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "LLyaudet",
    "github_project": "RatioDelta",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "ratio-delta"
}
        
Elapsed time: 0.50589s