Rocksolid Light

Welcome to novaBBS (click a section below)

mail  files  register  newsreader  groups  login

Message-ID:  

Polymer physicists are into chains.


devel / comp.lang.c / Re: Can this program be improved?

SubjectAuthor
* Can this program be improved?Manu Raju
+* Re: Can this program be improved?Andrey Tarasevich
|+- Re: Can this program be improved?David Brown
|+- Re: Can this program be improved?Tim Rentsch
|+- Re: Can this program be improved?Manfred
|+* Re: Can this program be improved?Manu Raju
||`* Re: Can this program be improved?Lew Pitcher
|| `* Re: Can this program be improved?Manu Raju
||  +- Re: Can this program be improved?Bart
||  +- Re: Can this program be improved?Richard Damon
||  `- Re: Can this program be improved?Lew Pitcher
|`* Re: Can this program be improved?Guillaume
| `* Re: Can this program be improved?Bart
|  +* Re: Can this program be improved?Andrey Tarasevich
|  |+* Re: Can this program be improved?James Kuyper
|  ||`* Re: Can this program be improved?Andrey Tarasevich
|  || `- Re: Can this program be improved?David Brown
|  |`* Re: Can this program be improved?Bart
|  | `- Re: Can this program be improved?Bart
|  `* Re: Can this program be improved?Keith Thompson
|   +* Re: Can this program be improved?Bart
|   |+* Re: Can this program be improved?Scott Lurndal
|   ||+- Re: Can this program be improved?Keith Thompson
|   ||`* Re: Can this program be improved?Kaz Kylheku
|   || `* Re: Can this program be improved?Bart
|   ||  `* Re: Can this program be improved?Kaz Kylheku
|   ||   `- Re: Can this program be improved?Bart
|   |`* Re: Can this program be improved?Keith Thompson
|   | +* Re: Can this program be improved?Kaz Kylheku
|   | |`* Re: Can this program be improved?Keith Thompson
|   | | `- Re: Can this program be improved?Kaz Kylheku
|   | `* Re: Can this program be improved?Bart
|   |  +- Re: Can this program be improved?Malcolm McLean
|   |  `* Re: Can this program be improved?Manfred
|   |   `* Re: Can this program be improved?Bart
|   |    +- Re: Can this program be improved?Manfred
|   |    `* Re: Can this program be improved?James Kuyper
|   |     `* Re: Can this program be improved?Bart
|   |      +- Re: Can this program be improved?james...@alumni.caltech.edu
|   |      `* Re: Can this program be improved?Keith Thompson
|   |       `* Re: Can this program be improved?Bart
|   |        `* Re: Can this program be improved?Keith Thompson
|   |         +* Re: Can this program be improved?Malcolm McLean
|   |         |`* Re: Can this program be improved?Keith Thompson
|   |         | `* Re: Can this program be improved?Malcolm McLean
|   |         |  +* Re: Can this program be improved?Keith Thompson
|   |         |  |`* Re: Can this program be improved?Malcolm McLean
|   |         |  | +- Re: Can this program be improved?Scott Lurndal
|   |         |  | `* Re: Can this program be improved?Keith Thompson
|   |         |  |  +* Re: Can this program be improved?Malcolm McLean
|   |         |  |  |+* Re: Can this program be improved?Kenny McCormack
|   |         |  |  ||`* Re: Can this program be improved?Malcolm McLean
|   |         |  |  || `- Re: Can this program be improved?Kenny McCormack
|   |         |  |  |+- Re: Can this program be improved?David Brown
|   |         |  |  |`* Re: Can this program be improved?Keith Thompson
|   |         |  |  | `* Re: Can this program be improved?Malcolm McLean
|   |         |  |  |  +- Re: Can this program be improved?Öö Tiib
|   |         |  |  |  +* Re: Can this program be improved?Mateusz Viste
|   |         |  |  |  |`* Re: Can this program be improved?Guillaume
|   |         |  |  |  | +* Re: Can this program be improved?Malcolm McLean
|   |         |  |  |  | |`* Re: Can this program be improved?Keith Thompson
|   |         |  |  |  | | +* Re: Can this program be improved?Malcolm McLean
|   |         |  |  |  | | |`* Re: Can this program be improved?Keith Thompson
|   |         |  |  |  | | | `- Re: Can this program be improved?Malcolm McLean
|   |         |  |  |  | | `- Re: Can this program be improved?Scott Lurndal
|   |         |  |  |  | `* Re: Can this program be improved?Bart
|   |         |  |  |  |  `* Re: Can this program be improved?Malcolm McLean
|   |         |  |  |  |   +* Re: Can this program be improved?Scott Lurndal
|   |         |  |  |  |   |`* Re: Can this program be improved?Malcolm McLean
|   |         |  |  |  |   | `- Re: Can this program be improved?Guillaume
|   |         |  |  |  |   `* Re: Can this program be improved?Bart
|   |         |  |  |  |    +- Re: Can this program be improved?Scott Lurndal
|   |         |  |  |  |    `- Re: Can this program be improved?Manfred
|   |         |  |  |  `* Re: Can this program be improved?David Brown
|   |         |  |  |   `* Re: Can this program be improved?Malcolm McLean
|   |         |  |  |    +* Re: Can this program be improved?David Brown
|   |         |  |  |    |`* Re: Can this program be improved?Malcolm McLean
|   |         |  |  |    | `* Re: Can this program be improved?David Brown
|   |         |  |  |    |  `- Re: Can this program be improved?Kenny McCormack
|   |         |  |  |    `- Re: Can this program be improved?Kenny McCormack
|   |         |  |  `- Re: Can this program be improved?Kenny McCormack
|   |         |  `* Re: Can this program be improved?Mateusz Viste
|   |         |   `* Re: Can this program be improved?Malcolm McLean
|   |         |    `* Re: Can this program be improved?David Brown
|   |         |     `* Re: Can this program be improved?Malcolm McLean
|   |         |      +* Re: Can this program be improved?Mateusz Viste
|   |         |      |+- Re: Can this program be improved?Bart
|   |         |      |`* Re: Can this program be improved?Malcolm McLean
|   |         |      | `* Re: Can this program be improved?Mateusz Viste
|   |         |      |  `- Re: Can this program be improved?Malcolm McLean
|   |         |      `* Re: Can this program be improved?Scott Lurndal
|   |         |       `- Re: Can this program be improved?Kenny McCormack
|   |         `- Re: Can this program be improved?Bart
|   `- Re: Can this program be improved?Kaz Kylheku
+* Re: Can this program be improved?Bart
|`- Re: Can this program be improved?Manu Raju
+* Re: Can this program be improved?Lew Pitcher
|+* Re: Can this program be improved?Öö Tiib
||+* Re: Can this program be improved?Lew Pitcher
|||`- Re: Can this program be improved?Öö Tiib
||`* Re: Can this program be improved?Chris M. Thomasson
|+* Re: Can this program be improved?Stefan Ram
|+- Re: Can this program be improved?Andrey Tarasevich
|`- Re: Can this program be improved?Manu Raju
+* Re: Can this program be improved?Tim Rentsch
+* Re: Can this program be improved?Malcolm McLean
`- Re: Can this program be improved?Lew Pitcher

Pages:12345
Re: Can this program be improved?

<sqafdf$qtd$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19654&group=comp.lang.c#19654

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: lew.pitc...@digitalfreehold.ca (Lew Pitcher)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Sun, 26 Dec 2021 19:22:23 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 69
Message-ID: <sqafdf$qtd$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqae28$g83$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Injection-Date: Sun, 26 Dec 2021 19:22:23 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="92ddfe9a5f125766f689ba1cafe032db";
logging-data="27565"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/r1Du1fmuRw1O35dSSyEse26JfWXh9sTg="
User-Agent: Pan/0.139 (Sexual Chocolate; GIT bf56508
git://git.gnome.org/pan2)
Cancel-Lock: sha1:lL10lkN00FxsRYShnOFtJwkOIAs=
 by: Lew Pitcher - Sun, 26 Dec 2021 19:22 UTC

On Sun, 26 Dec 2021 18:52:14 +0000, Manu Raju wrote:

> On 25/12/2021 05:44, Andrey Tarasevich wrote:
>> On 12/24/2021 5:00 PM, Manu Raju wrote:
>>>>
>>>> #include <stdio.h>
>>>> #include <stdlib.h>
>>>> #include <math.h>
>>>>
>>>> int main()
>>>> {
>>>>    float P = 100000; // Loan Amount
>>>>    float r = 7.5; // Advertised Interest Rate
>>>>    int n = 12; // Loan Period
>>>>    float payBack = (P * r / 1200 * pow(1 + r / 1200, n)) / (pow((1 +
>>>> r / 1200), n) - 1);
>>>>    float Opening = P; // Opening Balance
>>>>    float closing = 0;  // Closing Balance
>>>>    float interest = 0;
>>>>    float Total = 0;
>>>>    float repaid = 0;
>>>>
>>>>    printf("\nMonthly payment is: %.2f\n", payBack);
>>>>
>>>>      printf("%10s %14s %13s %10s %14s %12s\n", "Month", "Beginning",
>>>> "Interest", "Total", "Repayment", "Balance");
>>>>
>>>>      for (int i = 1; i <= n; i++)
>>>>      {
>>>>          for (int j = 0; j <= n; j++)
>>>>          {
>>>>              interest = Opening * r / 1200;
>>>>              Total = Opening + interest;
>>>>              repaid = payBack;
>>>>              closing = Total - payBack;
>>>>          }
>>>>          printf("%10d %14.0f %13.0f %10.0f %14.0f %12.0f\n", i,
>>>> Opening, interest, Total, repaid, closing);
>>>>          Opening = closing;
>>>>      }
>>>>      return 0;
>>>> }
>>
>>
>> 9. "Magical constants"? What on Earth is `1200`?
>
>
> It is just a figure 12 * 100. You first need to convert percentage into
> decimals by dividing by 100; Then you need to divide the number again by
> 12 to give monthly rate. Interest rate is normally annual rate. Hope
> this explains the magic number.

Well, you've explained it to us, but not to whomever will read your program next.

A good part of the art of programming is writing readable code; readable to you,
readable to you in 5 years from now, readable to the programmer that has to make
the next change to it, readable to the programmer who has to fix the bug in it.

Your use of 1200 is confusing, unless you already know that it facilitates the
conversion of a yearly interest rate expressed as a percent into a monthly
interest rate expressed as a decimal. It is worth noting that, should you
change the loan period expressed in P, you would /also/ have to change this
1200 "magic number" appropriately (or is P a "loan period in years"? if so,
then I believe that your interest calculations are wrong.)

--
Lew Pitcher
"In Skills, We Trust"

Re: Can this program be improved?

<sqanf8$9gs$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19657&group=comp.lang.c#19657

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: MR...@invalid.invalid (Manu Raju)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Sun, 26 Dec 2021 21:30:00 +0000
Organization: Aioe.org NNTP Server
Lines: 72
Message-ID: <sqanf8$9gs$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqae28$g83$1@dont-email.me> <sqafdf$qtd$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain;
Content-Transfer-Encoding: 7bit
Injection-Date: Sun, 26 Dec 2021 21:39:52 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="ad769829b7da17e43deaa7750baa4522";
logging-data="9756"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18awp46Dtusw2wZ8ZBw2JbfMTWjl0CjoiA="
Cancel-Lock: sha1:bWcGAtJKJ/dBAIax8rKnuP1hMsE=
In-Reply-To: <sqafdf$qtd$1@dont-email.me>
Content-Language: en-US
 by: Manu Raju - Sun, 26 Dec 2021 21:30 UTC

On 26/12/2021 19:22, Lew Pitcher wrote:
>
>
> Your use of 1200 is confusing, unless you already know that it facilitates the
> conversion of a yearly interest rate expressed as a percent into a monthly
> interest rate expressed as a decimal. It is worth noting that, should you
> change the loan period expressed in P, you would /also/ have to change this
> 1200 "magic number" appropriately (or is P a "loan period in years"? if so,
> then I believe that your interest calculations are wrong.)
>
>

The figure of 1200 will NEVER change. There will always be 12 months in
a year and we will always have to divide by 100 to express percentage as
decimals.

The interest rate can change and period (I used n) can also change. I used (n = 12) in my program to fit the table for people to see but
you can have 360 (30 years * 12). The program will still work.

Tim did a very good job to write a function. Did you see it? It is here.

<===========================================================================================>

void show_payment_table(double amount, double yearly_percentage_rate,
int months)
{ double const monthly_rate = yearly_percentage_rate / 100 / 12;
double const compounded = pow(1 + monthly_rate, months);
double const adjustment = compounded / (compounded - 1);
double const payment = amount * monthly_rate * adjustment;

double balance = amount;

printf("\nMonthly payment is: %.2f\n", payment);

printf("%10s %14s %13s %10s %14s %12s\n",
"Month", "Beginning", "Interest", "Total", "Repayment",
"Balance");

for (int i = 1; i <= months; i++)
{
double const interest = balance * monthly_rate;
double const owing = balance + interest;
double const remaining = owing - payment;

printf("%10d %14.2f %13.2f %10.2f %14.2f %12.2f\n",
i, balance, interest, owing, payment, remaining);
balance = remaining;
}

<===========================================================================================>

Now in the main function you just need to use it like so:

<===========================================================================================>

show_payment_table(250000, 5.0, 360);

<===========================================================================================>

This program is part of a big project where users will insert their
figures to calculate their repayments. all they need to enter will be
the Loan Amount, Interest Rate, and the Duration of the Loan. the
program will give them the schedule they can base their decision on. The
Windows Form/WPF will be used for these entries and "ASP.Net/MVC" for
the web site.

Best regards and have a very Happy New Year.

Re: Can this program be improved?

<sqaoqb$hd5$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19661&group=comp.lang.c#19661

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: bc...@freeuk.com (Bart)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Sun, 26 Dec 2021 22:02:51 +0000
Organization: A noiseless patient Spider
Lines: 23
Message-ID: <sqaoqb$hd5$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqae28$g83$1@dont-email.me> <sqafdf$qtd$1@dont-email.me>
<sqanf8$9gs$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Sun, 26 Dec 2021 22:02:51 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="f1b6d364d5a9a685cd779543a9ebe36d";
logging-data="17829"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/QaS725n2YsYOigvQdqSgYnW9oxeI0iEo="
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.4.0
Cancel-Lock: sha1:4lgotkiSHo2DiyjxxvllWvLby4k=
In-Reply-To: <sqanf8$9gs$1@dont-email.me>
 by: Bart - Sun, 26 Dec 2021 22:02 UTC

On 26/12/2021 21:30, Manu Raju wrote:
> On 26/12/2021 19:22, Lew Pitcher wrote:
>>
>>
>> Your use of 1200 is confusing, unless you already know that it facilitates the
>> conversion of a yearly interest rate expressed as a percent into a monthly
>> interest rate expressed as a decimal. It is worth noting that, should you
>> change the loan period expressed in P, you would /also/ have to change this
>> 1200 "magic number" appropriately (or is P a "loan period in years"? if so,
>> then I believe that your interest calculations are wrong.)
>>
>>
>
> The figure of 1200 will NEVER change. There will always be 12 months in
> a year and we will always have to divide by 100 to express percentage as
> decimals.

Imagine this is part of a bigger program, and the constant 1200 also
occurs elsewhere with a different meaning.

/That/ 1200 might need to change, but now you don't know which 1200s are
relevant.

Re: Can this program be improved?

<uQ6yJ.190873$3q9.17755@fx47.iad>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19662&group=comp.lang.c#19662

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!aioe.org!news.uzoreto.com!newsfeed.xs4all.nl!newsfeed7.news.xs4all.nl!news-out.netnews.com!news.alt.net!fdc2.netnews.com!peer02.ams1!peer.ams1.xlned.com!news.xlned.com!peer03.iad!feed-me.highwinds-media.com!news.highwinds-media.com!fx47.iad.POSTED!not-for-mail
MIME-Version: 1.0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:91.0)
Gecko/20100101 Thunderbird/91.4.1
Subject: Re: Can this program be improved?
Content-Language: en-US
Newsgroups: comp.lang.c
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqae28$g83$1@dont-email.me> <sqafdf$qtd$1@dont-email.me>
<sqanf8$9gs$1@dont-email.me>
From: Rich...@Damon-Family.org (Richard Damon)
In-Reply-To: <sqanf8$9gs$1@dont-email.me>
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Lines: 23
Message-ID: <uQ6yJ.190873$3q9.17755@fx47.iad>
X-Complaints-To: abuse@easynews.com
Organization: Forte - www.forteinc.com
X-Complaints-Info: Please be sure to forward a copy of ALL headers otherwise we will be unable to process your complaint properly.
Date: Sun, 26 Dec 2021 18:24:12 -0500
X-Received-Bytes: 2019
 by: Richard Damon - Sun, 26 Dec 2021 23:24 UTC

On 12/26/21 4:30 PM, Manu Raju wrote:
> The figure of 1200 will NEVER change. There will always be 12 months in
> a year and we will always have to divide by 100 to express percentage as
> decimals.

Actually that is a BIG assumption, that assumes that the ONLY payment
schedule is monthly.

Some people take out loans with Semi-Monthly (or B-Weekly) payment
schedules to pay things off a bit faster it that is how they get paid.

You might even choose weekly, or some are paid annually or things in
between.

All these change the 1200 to something else, to something like 100 *
payments_per_year.

Also, due to how common other operations on interest rates are, it may
make more sense on a program scale to do the rate/100 early in the
program and internally store these rates as the actual rate in per unit,
instead of the artificail percent (that would also allow parts of the
code to use permill if that was desired (per mill is per 1000 instead of
percent which is per 100).

Re: Can this program be improved?

<sqb2f3$qtd$2@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19664&group=comp.lang.c#19664

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: lew.pitc...@digitalfreehold.ca (Lew Pitcher)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Mon, 27 Dec 2021 00:47:31 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 49
Message-ID: <sqb2f3$qtd$2@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqae28$g83$1@dont-email.me> <sqafdf$qtd$1@dont-email.me>
<sqanf8$9gs$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Injection-Date: Mon, 27 Dec 2021 00:47:31 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="b5c79530520dff03aa345f9a0be64622";
logging-data="27565"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+4R6fGI76t5B0Hc9laQpp1yGMl+YtDCwA="
User-Agent: Pan/0.139 (Sexual Chocolate; GIT bf56508
git://git.gnome.org/pan2)
Cancel-Lock: sha1:xKByKnoD2t3sULpeHv1aEcfLbsI=
 by: Lew Pitcher - Mon, 27 Dec 2021 00:47 UTC

On Sun, 26 Dec 2021 21:30:00 +0000, Manu Raju wrote:

> On 26/12/2021 19:22, Lew Pitcher wrote:
>>
>>
>> Your use of 1200 is confusing, unless you already know that it facilitates the
>> conversion of a yearly interest rate expressed as a percent into a monthly
>> interest rate expressed as a decimal. It is worth noting that, should you
>> change the loan period expressed in P, you would /also/ have to change this
>> 1200 "magic number" appropriately (or is P a "loan period in years"? if so,
>> then I believe that your interest calculations are wrong.)
>>
>>
>
> The figure of 1200 will NEVER change. There will always be 12 months in
> a year and we will always have to divide by 100 to express percentage as
> decimals.

30 years ago, when I bought my house, I took out a mortgage. The bank offered
me options to pay in monthly installments, or bi-weekly installments. The bi-weekly
installment option offered a lower individual payment, but at a higher frequency.

So, /yes/, the number of installments per cycle /may/ change.

As for 1200 being an appropriate figure, I disagree. Your 1200 represents /two/
distinct conversion factors. Speaking from a purely "design" point of view, you
never want constants to represent more than one thing.

In this case, your 1200 represents
a) the conversion factor that alters values expressed as a percent into values
expressed as a decimal, and
b) the conversion factor that alters values expressed as a year into values
expressed as a number of months.

While it may be convenient for /you/ to consolidate those two conversion factors
into one constant, that consolidation /is not/ obvious, and /can/ lead to issues
if one or the other of those two conversions change.

Remember, you are writing code to be /readable/. The computer doesn't care; it
doesn't know C from COBOL or Brainfuck: it only knows the ones and zeros that
represent it's internal language. What you write must be readable and comprehensible
to other programmers.

[snip]

--
Lew Pitcher
"In Skills, We Trust"

Re: Can this program be improved?

<sqhuee$mht$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19665&group=comp.lang.c#19665

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: lew.pitc...@digitalfreehold.ca (Lew Pitcher)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Wed, 29 Dec 2021 15:21:50 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 27
Message-ID: <sqhuee$mht$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Injection-Date: Wed, 29 Dec 2021 15:21:50 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="ee8454cfa04b7291f304ea0159b197d6";
logging-data="23101"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+cnRv6+RFdgsqbfARwElp0bxgZCDTGNM4="
User-Agent: Pan/0.139 (Sexual Chocolate; GIT bf56508
git://git.gnome.org/pan2)
Cancel-Lock: sha1:zUfm82Iq7BZioeFPXCFPQcUhByM=
 by: Lew Pitcher - Wed, 29 Dec 2021 15:21 UTC

One last thought....

On Sat, 25 Dec 2021 01:00:00 +0000, Manu Raju wrote:

[snip]
>>   float payBack = (P * r / 1200 * pow(1 + r / 1200, n)) / (pow((1 + r / 1200), n) - 1);
[snip]

You need some documentation, especially around the important but obscure
parts like the statement above.

While I've been out of the financial computing world for quite some time,
I still can recognize /parts/ of this statement as relating to compound
interest calculations, but the /exact/ calculation escapes me.

A comment within your code, describing the sort of calculation you make
here, along with a reference to it's source, would go a long way to
making the program readable.

When you come back to this code next year, or when your teacher
evaluates the code, such a comment would make the intent of this
calculation clearer (and perhaps even assist in debugging).

HTH
--
Lew Pitcher
"In Skills, We Trust"

Re: Can this program be improved?

<sqi3p9$1bia$1@gioia.aioe.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19666&group=comp.lang.c#19666

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!aioe.org!UgLt14+w9tVHe1BtIa3HDQ.user.46.165.242.75.POSTED!not-for-mail
From: mess...@bottle.org (Guillaume)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Wed, 29 Dec 2021 17:52:54 +0100
Organization: Aioe.org NNTP Server
Message-ID: <sqi3p9$1bia$1@gioia.aioe.org>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Info: gioia.aioe.org; logging-data="44618"; posting-host="UgLt14+w9tVHe1BtIa3HDQ.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.4.1
Content-Language: fr
X-Notice: Filtered by postfilter v. 0.9.2
 by: Guillaume - Wed, 29 Dec 2021 16:52 UTC

Le 25/12/2021 à 06:44, Andrey Tarasevich a écrit :
> On 12/24/2021 5:00 PM, Manu Raju wrote:
>>>
>>> #include <stdio.h>
>>> #include <stdlib.h>
>>> #include <math.h>
>>>
>>> int main()
>>> {
>>>    float P = 100000; // Loan Amount
>>>    float r = 7.5; // Advertised Interest Rate
>>>    int n = 12; // Loan Period
>>>    float payBack = (P * r / 1200 * pow(1 + r / 1200, n)) / (pow((1 +
>>> r / 1200), n) - 1);
>>>    float Opening = P; // Opening Balance
>>>    float closing = 0;  // Closing Balance
>>>    float interest = 0;
>>>    float Total = 0;
>>>    float repaid = 0;
>>>
>>>    printf("\nMonthly payment is: %.2f\n", payBack);
>>>
>>>      printf("%10s %14s %13s %10s %14s %12s\n", "Month", "Beginning",
>>> "Interest", "Total", "Repayment", "Balance");
>>>
>>>      for (int i = 1; i <= n; i++)
>>>      {
>>>          for (int j = 0; j <= n; j++)
>>>          {
>>>              interest = Opening * r / 1200;
>>>              Total = Opening + interest;
>>>              repaid = payBack;
>>>              closing = Total - payBack;
>>>          }
>>>          printf("%10d %14.0f %13.0f %10.0f %14.0f %12.0f\n", i,
>>> Opening, interest, Total, repaid, closing);
>>>          Opening = closing;
>>>      }
>>>      return 0;
>>> }
>
> Certainly.
>
> 1. int main(void)
>
> 2. Stop using `float` for local variables. "Default" floating-point type
> in C is `double`. Everything else is used only if you have a good reason
> to do that. In this case you don't.
>
> 3. Stop using "regular" floating point types for representing monetary
> quantities. They are not good for that purpose.
>
> 4. It appears that you are actually trying to use `float` to represent
> _integer_ quantities (judging by your `printf`). Why?
>
> 5. Stop using `pow` for calculating integer powers. You don't really
> need `<math.h>` here.
>
> 6. Stop piling up all variable declarations at the beginning of the
> function. Declare variables as locally as possible.
>
> 7. Stop using dummy initializers for your variables. It is better to
> leave them uninitialized than initialize them to dummy zeros. This point
> is actually connected to the previous one: once you start declaring
> variables as locally as possible, you'll normally have a meaningful
> initializers for them at the point of declaration.
>
> 8. What's going on with capitalization in your variables names?
> `Opening`, `closing`, `interest`, `Total`? Is this a convention of some
> sort?
>
> 9. "Magical constants"? What on Earth is `1200`?
>
> 10. Repetitive subexpressions, like `1 + r / 1200` (some explicit, some
> slightly obfuscated) are probably a matter of style.... But anyway: DRY
> - do not repeat yourself.

All good points!

Re: Can this program be improved?

<sqi72e$q7e$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19667&group=comp.lang.c#19667

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: bc...@freeuk.com (Bart)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Wed, 29 Dec 2021 17:49:03 +0000
Organization: A noiseless patient Spider
Lines: 87
Message-ID: <sqi72e$q7e$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Date: Wed, 29 Dec 2021 17:49:03 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="78cafdbd687662625b70dae36cd7c08a";
logging-data="26862"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+Wq48QO1Xcv8mm9P81/j/EWG0SEyOvFvQ="
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.4.0
Cancel-Lock: sha1:IOU0O58LsxchiJyqSjBUeuwr1ME=
In-Reply-To: <sqi3p9$1bia$1@gioia.aioe.org>
 by: Bart - Wed, 29 Dec 2021 17:49 UTC

On 29/12/2021 16:52, Guillaume wrote:
> Le 25/12/2021 à 06:44, Andrey Tarasevich a écrit :

>> 1. int main(void)
>>
>> 2. Stop using `float` for local variables. "Default" floating-point
>> type in C is `double`. Everything else is used only if you have a good
>> reason to do that. In this case you don't.
>>
>> 3. Stop using "regular" floating point types for representing monetary
>> quantities. They are not good for that purpose.
>>
>> 4. It appears that you are actually trying to use `float` to represent
>> _integer_ quantities (judging by your `printf`). Why?
>>
>> 5. Stop using `pow` for calculating integer powers. You don't really
>> need `<math.h>` here.
>>
>> 6. Stop piling up all variable declarations at the beginning of the
>> function. Declare variables as locally as possible.
>>
>> 7. Stop using dummy initializers for your variables. It is better to
>> leave them uninitialized than initialize them to dummy zeros. This
>> point is actually connected to the previous one: once you start
>> declaring variables as locally as possible, you'll normally have a
>> meaningful initializers for them at the point of declaration.
>>
>> 8. What's going on with capitalization in your variables names?
>> `Opening`, `closing`, `interest`, `Total`? Is this a convention of
>> some sort?
>>
>> 9. "Magical constants"? What on Earth is `1200`?
>>
>> 10. Repetitive subexpressions, like `1 + r / 1200` (some explicit,
>> some slightly obfuscated) are probably a matter of style.... But
>> anyway: DRY - do not repeat yourself.
>
> All good points!
>

All?

2) Nothing wrong with using 'float' when it's appropropriate. Many
libraries eg. OpenGL make extensive use of float.

It's not obvious that C's /default/ float type is 'double', nor that
'float' is not the default float type, despite the name!

However, for this application, float is not quite accurate enough.

3) Double is perfectly suitable for representing monetary amounts,
especially in a toy program or for personal use. (I've used it for
accounts within a small business.)

But what exactly would be a practical alternative here? To import a
decimal float library, or somehow work with int64 whole cents? (Good
luck with interest calculations with that.)

4) Doesn't make sense. The quantities have to be floating point, but are
simply being printed with zero decimal places, as whole dollars or whatever.

5) I can't see an issue in using pow() to do pow(float,int); the result
will not be exact anyway. What is the alternate, to invent a local
powint(float,int) routine? Which will probably contain a loop. Or change
the logic for an accumulative product. pow() is simpler!

6) I just don't agree with this at all. I like all the cluttery
declarations out of the way of the logic, and in one place for quick
reference. Then you also know there are no multiple, incompatible
instances of any local identifier.

7) I think initialisers are a good idea. Some languages will ensure such
locals are set to a known starting value, like 0 or 0.0 for static
types; presumably they think that is a benefit.

Ones like (1) I agree with, but I also think it's a waste of time
pointing it out, as the practice is so widespread.

Because compilers [not mine!] have long routinely accepted () parameter
lists without any warnings that args passed to those functions are
completely unchecked for number or types, most seem to assume that they
mean /no/ parameters.

In this example program, it means that the code could call main(10,
20.0, "three") without comment. But then it could still call it legally
as main() if the (void) was added.

Re: Can this program be improved?

<sqid71$bnf$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19668&group=comp.lang.c#19668

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: andreyta...@hotmail.com (Andrey Tarasevich)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Wed, 29 Dec 2021 11:33:52 -0800
Organization: A noiseless patient Spider
Lines: 103
Message-ID: <sqid71$bnf$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 8bit
Injection-Date: Wed, 29 Dec 2021 19:33:53 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="94c5554e57bb6a49781007bcd3718b83";
logging-data="12015"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19++Plc7e9Mca6XSlxs6ZC5"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.4.1
Cancel-Lock: sha1:3cHmlZVKQMCb3QwvSg7z08b2zV0=
In-Reply-To: <sqi72e$q7e$1@dont-email.me>
Content-Language: en-US
 by: Andrey Tarasevich - Wed, 29 Dec 2021 19:33 UTC

On 12/29/2021 9:49 AM, Bart wrote:
> On 29/12/2021 16:52, Guillaume wrote:
>> Le 25/12/2021 à 06:44, Andrey Tarasevich a écrit :
>
>
>>> 1. int main(void)
>>>
>>> 2. Stop using `float` for local variables. "Default" floating-point
>>> type in C is `double`. Everything else is used only if you have a
>>> good reason to do that. In this case you don't.
>>>
>>> 3. Stop using "regular" floating point types for representing
>>> monetary quantities. They are not good for that purpose.
>>>
>>> 4. It appears that you are actually trying to use `float` to
>>> represent _integer_ quantities (judging by your `printf`). Why?
>>>
>>> 5. Stop using `pow` for calculating integer powers. You don't really
>>> need `<math.h>` here.
>>>
>>> 6. Stop piling up all variable declarations at the beginning of the
>>> function. Declare variables as locally as possible.
>>>
>>> 7. Stop using dummy initializers for your variables. It is better to
>>> leave them uninitialized than initialize them to dummy zeros. This
>>> point is actually connected to the previous one: once you start
>>> declaring variables as locally as possible, you'll normally have a
>>> meaningful initializers for them at the point of declaration.
>>>
>>> 8. What's going on with capitalization in your variables names?
>>> `Opening`, `closing`, `interest`, `Total`? Is this a convention of
>>> some sort?
>>>
>>> 9. "Magical constants"? What on Earth is `1200`?
>>>
>>> 10. Repetitive subexpressions, like `1 + r / 1200` (some explicit,
>>> some slightly obfuscated) are probably a matter of style.... But
>>> anyway: DRY - do not repeat yourself.
>>
>> All good points!
>>
>
> 2) Nothing wrong with using 'float' when it's appropropriate. Many
> libraries eg. OpenGL make extensive use of float.

That's just emphasizes my the point. The main purpose of "small" types,
like `float`, `short`, char as plain integer, bit-fields etc. is to save
memory in quantitatively massive data structures.

That's exactly what OpenGL is intended to work with: massive amounts of
geometric data. That's why it opts for `float` Everything else is just a
consequence of that.

> It's not obvious that C's /default/ float type is 'double', nor that
> 'float' is not the default float type, despite the name!

It doesn't have to be obvious. That's why I state it explicitly.

> 6) I just don't agree with this at all. I like all the cluttery
> declarations out of the way of the logic,

Declarations are never cluttery, unless you make a deliberate effort to
make them that.

> and in one place for quick reference.

Piling up all variable declarations in one place makes for much slower
reference: first, one has has to find the pile, then one has to sift
through the pile.

Local declarations are always instantly visible, making for much quicker
reference. Basically, with local declarations the matter of "reference"
is virtually non-existent: the required knowledge is almost always
naturally and intuitively present within the field of view.

The popular counter-argument stating that "functions have to be small
with small number of variables" is nothing else that a fake advice whose
only purpose is to serve as an emergency brace for the cracking and
crumbling bad practice of piling up variable declarations.

> Then you also know there are no multiple, incompatible
> instances of any local identifier.

This is a classic "solution looking for a problem": a solution for a
problem that does not really exist in the first place.

> 7) I think initialisers are a good idea. Some languages will ensure such
> locals are set to a known starting value, like 0 or 0.0 for static
> types; presumably they think that is a benefit.

It definitely has a benefit: it works as a bootstrapping point for
static/dynamic initialization. I.e. gives you a reliable anchoring
point: something that is guaranteed to be there "even before the
programs starts", without you having to worry about the initialization
and associated ordering issues. No other reason.

And this, of course, does not apply outside of static initialization
contexts. The only thing you achieve by using dummy initializers is
defeat checks performed by static/dynamic analysis tools.

--
Best regards,
Andrey Tarasevich

Re: Can this program be improved?

<87sfub2g2t.fsf@nosuchdomain.example.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19670&group=comp.lang.c#19670

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Keith.S....@gmail.com (Keith Thompson)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Wed, 29 Dec 2021 14:37:14 -0800
Organization: None to speak of
Lines: 42
Message-ID: <87sfub2g2t.fsf@nosuchdomain.example.com>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: reader02.eternal-september.org; posting-host="b7b2f4901df19a23ffe26ffd12faed25";
logging-data="21483"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+hn2Lje3aTv/gtZSy2t7jQ"
User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Cancel-Lock: sha1:J/9nYtT+osk+neK5kupI9HjGDjs=
sha1:2gNeC5uJzcW7IaSzszuWT3z567c=
 by: Keith Thompson - Wed, 29 Dec 2021 22:37 UTC

Bart <bc@freeuk.com> writes:
[...]
> 3) Double is perfectly suitable for representing monetary amounts,
> especially in a toy program or for personal use. (I've used it for
> accounts within a small business.)

In a toy program, sure -- and I'd say *only* in a toy program.

Using floating-point for money risks, at best, rare off-by-one errors,
such as a computation yielding a result one cent off from the correct
value. I believe that would be considered unacceptable in any
real-world financial application.

> But what exactly would be a practical alternative here? To import a
> decimal float library, or somehow work with int64 whole cents? (Good
> luck with interest calculations with that.)

If you only need to do calculations that yield whole numbers of cents,
then yes, you can use a wide integer (long long or uint64_t, for
example, or define your own type "in64" if you insist for some reason)
with a scaling factor of 100. If you need to do interest calculations
in the real world (not in a toy program), you need to find out the exact
rules for those calculations and implement them.

[...]

> 5) I can't see an issue in using pow() to do pow(float,int); the
> result will not be exact anyway. What is the alternate, to invent a
> local powint(float,int) routine? Which will probably contain a
> loop. Or change the logic for an accumulative product. pow() is
> simpler!

Integer exponentiation can be done exactly (assuming no overflow).
pow() can suffer floating-point errors. Whether pow() is acceptable
depends on the application and the financial rules governing it.

[...]

--
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
Working, but not speaking, for Philips
void Void(void) { Void(); } /* The recursive call of the void */

Re: Can this program be improved?

<sqiprq$1kk$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19671&group=comp.lang.c#19671

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: bc...@freeuk.com (Bart)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Wed, 29 Dec 2021 23:09:45 +0000
Organization: A noiseless patient Spider
Lines: 66
Message-ID: <sqiprq$1kk$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Wed, 29 Dec 2021 23:09:46 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="50a6f6e5a951aff34d7b2de53679ba6e";
logging-data="1684"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19t5riql/iislBC4UBMnBkaOE2em8jRdY0="
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.4.1
Cancel-Lock: sha1:cdf1i/xcCm0eeRhUDg3uvQ0lPZY=
In-Reply-To: <87sfub2g2t.fsf@nosuchdomain.example.com>
 by: Bart - Wed, 29 Dec 2021 23:09 UTC

On 29/12/2021 22:37, Keith Thompson wrote:
> Bart <bc@freeuk.com> writes:
> [...]
>> 3) Double is perfectly suitable for representing monetary amounts,
>> especially in a toy program or for personal use. (I've used it for
>> accounts within a small business.)
>
> In a toy program, sure -- and I'd say *only* in a toy program.
>
> Using floating-point for money risks, at best, rare off-by-one errors,
> such as a computation yielding a result one cent off from the correct
> value. I believe that would be considered unacceptable in any
> real-world financial application.

Real-world doesn't need to mean dealing with trillions of dollars to the
exact cent.

Most businesses work with amounts far smaller. Then I believe the
precision of float64 is enough to emulate the needed rounding methods.

(But I didn't even bother with that. My app anyway had to work with
multliple parallel currencies so if an amount was correct to the nearest
cent on one, it couldn't also be correct in another. But the environment
was also fairly informal.)

>> But what exactly would be a practical alternative here? To import a
>> decimal float library, or somehow work with int64 whole cents? (Good
>> luck with interest calculations with that.)
>
> If you only need to do calculations that yield whole numbers of cents,
> then yes, you can use a wide integer (long long or uint64_t, for
> example, or define your own type "in64" if you insist for some reason)
> with a scaling factor of 100. If you need to do interest calculations
> in the real world (not in a toy program), you need to find out the exact
> rules for those calculations and implement them.

I wouldn't know where to start to apply an interest rate specified to
multiple decimals, to an integer amount, to yield an integer result.

> [...]
>
>> 5) I can't see an issue in using pow() to do pow(float,int); the
>> result will not be exact anyway. What is the alternate, to invent a
>> local powint(float,int) routine? Which will probably contain a
>> loop. Or change the logic for an accumulative product. pow() is
>> simpler!
>
> Integer exponentiation can be done exactly (assuming no overflow).
> pow() can suffer floating-point errors. Whether pow() is acceptable
> depends on the application and the financial rules governing it.

This is integer exponentation of floating point values. The choice is
between repeated multiplications, or calling pow().

The latter is likely done with logs and exp() which can introduce
errors, but if I calculate 3% compound interest monthly over about 80
years, then the results of:

1.03 * 1.03 * ... // 1000 times

and:

pow(1.03, 1000)

differ only in the 16th significant digit.

Re: Can this program be improved?

<Cy6zJ.242630$IW4.143221@fx48.iad>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19672&group=comp.lang.c#19672

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!aioe.org!news.uzoreto.com!news-out.netnews.com!news.alt.net!fdc2.netnews.com!peer02.ams1!peer.ams1.xlned.com!news.xlned.com!peer02.iad!feed-me.highwinds-media.com!news.highwinds-media.com!fx48.iad.POSTED!not-for-mail
X-newsreader: xrn 9.03-beta-14-64bit
Sender: scott@dragon.sl.home (Scott Lurndal)
From: sco...@slp53.sl.home (Scott Lurndal)
Reply-To: slp53@pacbell.net
Subject: Re: Can this program be improved?
Newsgroups: comp.lang.c
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me> <sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me> <87sfub2g2t.fsf@nosuchdomain.example.com> <sqiprq$1kk$1@dont-email.me>
Lines: 29
Message-ID: <Cy6zJ.242630$IW4.143221@fx48.iad>
X-Complaints-To: abuse@usenetserver.com
NNTP-Posting-Date: Wed, 29 Dec 2021 23:54:10 UTC
Organization: UsenetServer - www.usenetserver.com
Date: Wed, 29 Dec 2021 23:54:10 GMT
X-Received-Bytes: 1912
 by: Scott Lurndal - Wed, 29 Dec 2021 23:54 UTC

Bart <bc@freeuk.com> writes:
>On 29/12/2021 22:37, Keith Thompson wrote:
>> Bart <bc@freeuk.com> writes:
>> [...]
>>> 3) Double is perfectly suitable for representing monetary amounts,
>>> especially in a toy program or for personal use. (I've used it for
>>> accounts within a small business.)
>>
>> In a toy program, sure -- and I'd say *only* in a toy program.
>>
>> Using floating-point for money risks, at best, rare off-by-one errors,
>> such as a computation yielding a result one cent off from the correct
>> value. I believe that would be considered unacceptable in any
>> real-world financial application.
>
>Real-world doesn't need to mean dealing with trillions of dollars to the
>exact cent.

Real-world still uses COBOL for these type of applications.

>
>Most businesses work with amounts far smaller. Then I believe the
>precision of float64 is enough to emulate the needed rounding methods.

Why bother with the error-prone "needed rounding methods". Use uint64_t
and denominate in mills.

If your domain requires larger numbers, widen it to 128 bits.

Re: Can this program be improved?

<87o84z2bsi.fsf@nosuchdomain.example.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19673&group=comp.lang.c#19673

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Keith.S....@gmail.com (Keith Thompson)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Wed, 29 Dec 2021 16:09:49 -0800
Organization: None to speak of
Lines: 92
Message-ID: <87o84z2bsi.fsf@nosuchdomain.example.com>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com> <sqiprq$1kk$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: reader02.eternal-september.org; posting-host="ef2881cf3a29f048a7861a1bf9688d75";
logging-data="17988"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18nBeZMKYIVRtE4Rb2pkuKG"
User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Cancel-Lock: sha1:4c1MLxm0Vbkxd1rvt+7dqBxeyno=
sha1:HZGVKS/MJQ38ulA+sm1Vc1AWDhI=
 by: Keith Thompson - Thu, 30 Dec 2021 00:09 UTC

Bart <bc@freeuk.com> writes:
> On 29/12/2021 22:37, Keith Thompson wrote:
>> Bart <bc@freeuk.com> writes:
>> [...]
>>> 3) Double is perfectly suitable for representing monetary amounts,
>>> especially in a toy program or for personal use. (I've used it for
>>> accounts within a small business.)
>> In a toy program, sure -- and I'd say *only* in a toy program.
>> Using floating-point for money risks, at best, rare off-by-one
>> errors,
>> such as a computation yielding a result one cent off from the correct
>> value. I believe that would be considered unacceptable in any
>> real-world financial application.
>
> Real-world doesn't need to mean dealing with trillions of dollars to
> the exact cent.

But it can mean dealing with thousands of dollars to the exact cent --
and if you get a result of $1234.565001 and round it to $1234.57, when
the rules call for a result of $1234.56, that could be a serious problem.

> Most businesses work with amounts far smaller. Then I believe the
> precision of float64 is enough to emulate the needed rounding methods.

Working with smaller amounts just means that errors like this are rarer,
not that they don't happen.

> (But I didn't even bother with that. My app anyway had to work with
> multliple parallel currencies so if an amount was correct to the
> nearest cent on one, it couldn't also be correct in another. But the
> environment was also fairly informal.)

If "fairly informal" means you don't need results accurate to the cent,
then floating-point might be good enough. But financial institutions
can't afford that.

>>> But what exactly would be a practical alternative here? To import a
>>> decimal float library, or somehow work with int64 whole cents? (Good
>>> luck with interest calculations with that.)
>> If you only need to do calculations that yield whole numbers of
>> cents,
>> then yes, you can use a wide integer (long long or uint64_t, for
>> example, or define your own type "in64" if you insist for some reason)
>> with a scaling factor of 100. If you need to do interest calculations
>> in the real world (not in a toy program), you need to find out the exact
>> rules for those calculations and implement them.
>
> I wouldn't know where to start to apply an interest rate specified to
> multiple decimals, to an integer amount, to yield an integer result.

Neither would I. My understanding is that there are precisely stated
rules that tell you exactly what results a given computation must
produce, for example when computing compound interest. If you're going
to be writing real-world software, where satisfying those rules is a
requirement, you *must* learn those rules first. (I haven't done so and
probably won't.)

>> [...]
>>
>>> 5) I can't see an issue in using pow() to do pow(float,int); the
>>> result will not be exact anyway. What is the alternate, to invent a
>>> local powint(float,int) routine? Which will probably contain a
>>> loop. Or change the logic for an accumulative product. pow() is
>>> simpler!
>> Integer exponentiation can be done exactly (assuming no overflow).
>> pow() can suffer floating-point errors. Whether pow() is acceptable
>> depends on the application and the financial rules governing it.
>
> This is integer exponentation of floating point values. The choice is
> between repeated multiplications, or calling pow().
>
> The latter is likely done with logs and exp() which can introduce
> errors, but if I calculate 3% compound interest monthly over about 80
> years, then the results of:
>
> 1.03 * 1.03 * ... // 1000 times
>
> and:
>
> pow(1.03, 1000)
>
> differ only in the 16th significant digit.

And if that difference in the 16th significant digit happens to
give you a result that's off by one cent after rounding, that's
a problem -- unless your environment is "fairly informal" and you
don't mind sometimes being off by a cent.

--
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
Working, but not speaking, for Philips
void Void(void) { Void(); } /* The recursive call of the void */

Re: Can this program be improved?

<87k0fn2bp9.fsf@nosuchdomain.example.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19674&group=comp.lang.c#19674

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Keith.S....@gmail.com (Keith Thompson)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Wed, 29 Dec 2021 16:11:46 -0800
Organization: None to speak of
Lines: 41
Message-ID: <87k0fn2bp9.fsf@nosuchdomain.example.com>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com> <sqiprq$1kk$1@dont-email.me>
<Cy6zJ.242630$IW4.143221@fx48.iad>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: reader02.eternal-september.org; posting-host="ef2881cf3a29f048a7861a1bf9688d75";
logging-data="17988"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/rrfqCJLaLtnbGYY8sT23m"
User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Cancel-Lock: sha1:eSKgOFDDB7NZZtMXvE+jz/Kc0XY=
sha1:tle35iLJ8lCCcjT+Bg9plkfHdXE=
 by: Keith Thompson - Thu, 30 Dec 2021 00:11 UTC

scott@slp53.sl.home (Scott Lurndal) writes:
> Bart <bc@freeuk.com> writes:
>>On 29/12/2021 22:37, Keith Thompson wrote:
>>> Bart <bc@freeuk.com> writes:
>>> [...]
>>>> 3) Double is perfectly suitable for representing monetary amounts,
>>>> especially in a toy program or for personal use. (I've used it for
>>>> accounts within a small business.)
>>>
>>> In a toy program, sure -- and I'd say *only* in a toy program.
>>>
>>> Using floating-point for money risks, at best, rare off-by-one errors,
>>> such as a computation yielding a result one cent off from the correct
>>> value. I believe that would be considered unacceptable in any
>>> real-world financial application.
>>
>>Real-world doesn't need to mean dealing with trillions of dollars to the
>>exact cent.
>
> Real-world still uses COBOL for these type of applications.
>
>>Most businesses work with amounts far smaller. Then I believe the
>>precision of float64 is enough to emulate the needed rounding methods.
>
> Why bother with the error-prone "needed rounding methods". Use uint64_t
> and denominate in mills.
>
> If your domain requires larger numbers, widen it to 128 bits.

Compound interest calculations can give intermediate results that are
not a whole number of cents or even mills, and those results must be
rounded to the nearest cent at some specified point using specified
rules. (And no, I don't know what those rules are.)

Using large integers representing cents or mills is find if all
you're doing is adding and subtracting.

--
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
Working, but not speaking, for Philips
void Void(void) { Void(); } /* The recursive call of the void */

Re: Can this program be improved?

<20211229160506.727@kylheku.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19675&group=comp.lang.c#19675

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: 480-992-...@kylheku.com (Kaz Kylheku)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Thu, 30 Dec 2021 00:29:32 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 70
Message-ID: <20211229160506.727@kylheku.com>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com>
Injection-Date: Thu, 30 Dec 2021 00:29:32 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="2552815f4ad3b8ad572252e71445a047";
logging-data="26278"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/vDOxhqHhW1I4omHakDwT6LDpr2fJh1WA="
User-Agent: slrn/1.0.3 (Linux)
Cancel-Lock: sha1:muNpKdn6mmiTRyCScZUyjuyNsDo=
 by: Kaz Kylheku - Thu, 30 Dec 2021 00:29 UTC

On 2021-12-29, Keith Thompson <Keith.S.Thompson+u@gmail.com> wrote:
> Bart <bc@freeuk.com> writes:
> [...]
>> 3) Double is perfectly suitable for representing monetary amounts,
>> especially in a toy program or for personal use. (I've used it for
>> accounts within a small business.)
>
> In a toy program, sure -- and I'd say *only* in a toy program.
>
> Using floating-point for money risks, at best, rare off-by-one errors,
> such as a computation yielding a result one cent off from the correct
> value. I believe that would be considered unacceptable in any
> real-world financial application.

The fear is not well-founded.

Let's for a moment set aside astronomical monetary figures, and say
we are just doing accounting for some ordinary business.

Suppose we use the representation that 1.0 == $1.00 USD.

A one-cent error in some ordinary amount like $15,123,13 is gapingly
huge. It's in the 9th digit out of an available 15.

If that were a problem, floating-point would be entirely unsuitable
for engineering and science.

(Side note: consider that people use Microsoft Excel for real financial
work, and go with those numbers.

https://en.wikipedia.org/wiki/Numeric_precision_in_Microsoft_Excel )

The double type can recored 15 decimal digits of precision.
We can store the amount $9,999,999,999,999.99 in a double and
get all of it back. Say, that to be safe against truncation
errors, we scale that back by two orders of magnitude. That
gives us $99,999,999,999.9999 being exactly representable:
99 billion dollars down to a hundredth of a cent. If the
accounting we are doing runs in the cents, we are fine.

What we have to watch out for is the accumulation of errors. For
instance, we cannot just blindly sum an arbitrary long column of
figures, such as the transactions in a long-running account. After every
calculation, we should fastidiously round the result to the nearest
penny. The calculation will already be vastly closer to that
penny, than to any other penny: we are talking about a very tiny
movement.

You can probably get away with letting error accumulate over many
calculations, without any risk that the approximation will jump to the
wrong penny. The safest thing is probably to nip it in the bud:
"snap" the result of every calculation to the "penny grid".

Ideally, every amount recoreded into the double-based ledger
should be that type's closest approximation of the intended
dollars-and-cents amount.

There are some additional issues in that when percentages or other
fractional values are calculated, the accounting system may be governed
by special rules about rounding: when a fractional result lands halfway
between two pennies, which one does it go to?

But this applies regardless of whether we use scaled integers or doubles
for the base amounts, and the requirements could be met with
careful double-based arithmetic.

--
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal

Re: Can this program be improved?

<20211229162959.990@kylheku.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19676&group=comp.lang.c#19676

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: 480-992-...@kylheku.com (Kaz Kylheku)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Thu, 30 Dec 2021 00:34:41 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 41
Message-ID: <20211229162959.990@kylheku.com>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com> <sqiprq$1kk$1@dont-email.me>
<Cy6zJ.242630$IW4.143221@fx48.iad>
Injection-Date: Thu, 30 Dec 2021 00:34:41 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="2552815f4ad3b8ad572252e71445a047";
logging-data="26278"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/64V/7EB+Wb6XwOMCkXSPeCbX/KOGVeZw="
User-Agent: slrn/1.0.3 (Linux)
Cancel-Lock: sha1:LosJ+9dzlANF6LNFA7Z915raFQ8=
 by: Kaz Kylheku - Thu, 30 Dec 2021 00:34 UTC

On 2021-12-29, Scott Lurndal <scott@slp53.sl.home> wrote:
> Bart <bc@freeuk.com> writes:
>>On 29/12/2021 22:37, Keith Thompson wrote:
>>> Bart <bc@freeuk.com> writes:
>>> [...]
>>>> 3) Double is perfectly suitable for representing monetary amounts,
>>>> especially in a toy program or for personal use. (I've used it for
>>>> accounts within a small business.)
>>>
>>> In a toy program, sure -- and I'd say *only* in a toy program.
>>>
>>> Using floating-point for money risks, at best, rare off-by-one errors,
>>> such as a computation yielding a result one cent off from the correct
>>> value. I believe that would be considered unacceptable in any
>>> real-world financial application.
>>
>>Real-world doesn't need to mean dealing with trillions of dollars to the
>>exact cent.
>
> Real-world still uses COBOL for these type of applications.
>
>>
>>Most businesses work with amounts far smaller. Then I believe the
>>precision of float64 is enough to emulate the needed rounding methods.
>
> Why bother with the error-prone "needed rounding methods". Use uint64_t
> and denominate in mills.

This common intution is incorrect. Financial systems sometimews need to
calculate fractional amounts, like a 15.03% tax or whatever.

And in those situations, you may be required to implement the required
rounding rules: what to do when some fractional result lands halfway
between two pennies: which one does it go to.

You cannot get away from rounding issues just because you used an
integer representation for mills or penies.

--
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal

Re: Can this program be improved?

<20211229163503.145@kylheku.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19677&group=comp.lang.c#19677

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: 480-992-...@kylheku.com (Kaz Kylheku)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Thu, 30 Dec 2021 00:59:50 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 72
Message-ID: <20211229163503.145@kylheku.com>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com> <sqiprq$1kk$1@dont-email.me>
<87o84z2bsi.fsf@nosuchdomain.example.com>
Injection-Date: Thu, 30 Dec 2021 00:59:50 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="2552815f4ad3b8ad572252e71445a047";
logging-data="2060"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19EmE1oDYkuyuw+vXZWSlbHdpUKnn7IdRM="
User-Agent: slrn/1.0.3 (Linux)
Cancel-Lock: sha1:9MCsNAP5nwRvPuWn+A53oDW1E8g=
 by: Kaz Kylheku - Thu, 30 Dec 2021 00:59 UTC

On 2021-12-30, Keith Thompson <Keith.S.Thompson+u@gmail.com> wrote:
> Bart <bc@freeuk.com> writes:
>> On 29/12/2021 22:37, Keith Thompson wrote:
>>> Bart <bc@freeuk.com> writes:
>>> [...]
>>>> 3) Double is perfectly suitable for representing monetary amounts,
>>>> especially in a toy program or for personal use. (I've used it for
>>>> accounts within a small business.)
>>> In a toy program, sure -- and I'd say *only* in a toy program.
>>> Using floating-point for money risks, at best, rare off-by-one
>>> errors,
>>> such as a computation yielding a result one cent off from the correct
>>> value. I believe that would be considered unacceptable in any
>>> real-world financial application.
>>
>> Real-world doesn't need to mean dealing with trillions of dollars to
>> the exact cent.
>
> But it can mean dealing with thousands of dollars to the exact cent --
> and if you get a result of $1234.565001 and round it to $1234.57, when

You cannot get a result of $1234.565... by only additive and subtractive
transactions, such as recording expenses in a ledger whose
denomination is pennies!

(Not unless you neglected to take care of cumulative truncation error
and let that error freely accumulate for a vast number of transactions.
But let's say everything was done right up to the point this $1234.565001
showed up.)

The way you got that half penny in there: 0.56 + 0.005001 is that
you performed a fractional calculation, like calculating a percentage
due to tax or interest or dividend or whatever.

If you calculate a fractional quantity, you must deal with the rounding,
right there and then, based on the applicable requirements.
(Whether or not you're recording monetary amounts using integers!)

For instance, let's suppose that 1234.565001 is the calculation of the
new account balance due to interest earned. The previous balance was
1232.19. Being recorded in the ledger, that fiture is exact. (Or, if we
use doubles, it is a vastly accurate approximation of 1232.19).

We calculated some interest and came up with 1234.565001. But we cannot
record that; the account is to the penny. So what do we do? We apply
some rounding rule, like Banker's Rounding.

If the result were exactly 1234.565, then according ot Banker's
Rounding, we would round down to 1234.56, because 6 is an even digit.
A 5 following an odd digit would go up.

This kind of thing you must handle even if the inputs amounts (other
than the percentage rate) are integers, and so are the outputs.

In the accounting system I wrote for my self-employment activities,
I used integers representing pennies, but fractionals are calculated
with the help of floating-point. I'm not required to deal with precise,d
decimal-based rounding rules, so what I did is this: the fractional
result (measuring pennies) is calculated in double-precision floating
point. Then this cents amount is subject to the C library round()
function to get it to the closest integer (i.e. cent), and then that is
converted to the integer-based monetary type.

I'm confident I could replace that integer-based monetary type with
floating-point and get all the same results (that would be fairly easily
checked, because the system calculates everything from scratch
from the recrded transaction log, every time it is run; my real data
could be converted to a giant regression test case.)

--
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal

Re: Can this program be improved?

<sqj0mf$532$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19678&group=comp.lang.c#19678

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: bc...@freeuk.com (Bart)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Thu, 30 Dec 2021 01:06:23 +0000
Organization: A noiseless patient Spider
Lines: 80
Message-ID: <sqj0mf$532$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com> <sqiprq$1kk$1@dont-email.me>
<87o84z2bsi.fsf@nosuchdomain.example.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Thu, 30 Dec 2021 01:06:23 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="50a6f6e5a951aff34d7b2de53679ba6e";
logging-data="5218"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+X/dOwOZCsd8d8B54INRT69/2h1dgddCc="
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.4.1
Cancel-Lock: sha1:P2pxfvSBo5Vt3KdY5CkVIoDOO+k=
In-Reply-To: <87o84z2bsi.fsf@nosuchdomain.example.com>
 by: Bart - Thu, 30 Dec 2021 01:06 UTC

On 30/12/2021 00:09, Keith Thompson wrote:
> Bart <bc@freeuk.com> writes:

>> Real-world doesn't need to mean dealing with trillions of dollars to
>> the exact cent.
>
> But it can mean dealing with thousands of dollars to the exact cent --
> and if you get a result of $1234.565001 and round it to $1234.57, when
> the rules call for a result of $1234.56, that could be a serious problem.

With floating point, that result could as easily be just under 1234.565
as just over. If the requirements really are that binary floating point
must have exactly identical results, down to the least significant bit,
even for intermediates so that rounding will always give the same
results too, then that's what you have to do.

But I don't believe the OP's program is in that class. (This is one of a
category of exercises, like hashes, prngs, and reading a line of input
of arbitrary length, where apparently nothing less that a perfect,
industrial-strength professional solution will do.)

>> Most businesses work with amounts far smaller. Then I believe the
>> precision of float64 is enough to emulate the needed rounding methods.
>
> Working with smaller amounts just means that errors like this are rarer,
> not that they don't happen.
>
>> (But I didn't even bother with that. My app anyway had to work with
>> multliple parallel currencies so if an amount was correct to the
>> nearest cent on one, it couldn't also be correct in another. But the
>> environment was also fairly informal.)
>
> If "fairly informal" means you don't need results accurate to the cent,
> then floating-point might be good enough. But financial institutions
> can't afford that.

You can easily get results to the nearest cent. The problem can be when
rounding errors or rounding methods result in discrepancies between
different approaches, or between different programs and languages.

I just don't think this is a programming issue, more one of requirements
and specification.

>> I wouldn't know where to start to apply an interest rate specified to
>> multiple decimals, to an integer amount, to yield an integer result.
>
> Neither would I. My understanding is that there are precisely stated
> rules that tell you exactly what results a given computation must
> produce, for example when computing compound interest. If you're going
> to be writing real-world software, where satisfying those rules is a
> requirement, you *must* learn those rules first. (I haven't done so and
> probably won't.)

Again with real-world. Is this a corner shop or is it Lloyds Bank? Or
someone working out figures for their tax return? Or doing a personal
budget?

(In my country, tax returns only need figures in whole pounds, and don't
need to be that exact. So long as you are not deliberately
misrepresenting by significant amounts, it doesn't matter if they are a
pound either way.)

So, what do you think the OP should do?

Remember this is floating point which is generally not exact: 1.00625
(the factor needed for 7.5% annual interest applied monthly) can't be
represented precisely IEEE754. Using long integers for this isn't a
magic bullet, since you still have to multiply by 1.00625.

As it turns out, I do have a clue how it's done: you multiply by 100625
and divide by 100000.

However, int64 or even int128 don't have enough range to multiply by
100625 N times before dividing by 100000 N times. You have to do the
divide at each step. Which means deciding what to do about the remainder
at each step (especially if negative numbers are involved).

It's back to specifications.

Re: Can this program be improved?

<87fsqa3lsi.fsf@nosuchdomain.example.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19679&group=comp.lang.c#19679

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Keith.S....@gmail.com (Keith Thompson)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Wed, 29 Dec 2021 17:48:29 -0800
Organization: None to speak of
Lines: 18
Message-ID: <87fsqa3lsi.fsf@nosuchdomain.example.com>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com> <sqiprq$1kk$1@dont-email.me>
<87o84z2bsi.fsf@nosuchdomain.example.com>
<20211229163503.145@kylheku.com>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: reader02.eternal-september.org; posting-host="ef2881cf3a29f048a7861a1bf9688d75";
logging-data="14773"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX198hAQEj1zx8Ij6dsan5W0r"
User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux)
Cancel-Lock: sha1:Qqai6c8sXp6HBUzgp6cgoqCv/j0=
sha1:BfBwEBDeigITXt/371SXrmQ2srw=
 by: Keith Thompson - Thu, 30 Dec 2021 01:48 UTC

Kaz Kylheku <480-992-1380@kylheku.com> writes:
> On 2021-12-30, Keith Thompson <Keith.S.Thompson+u@gmail.com> wrote:
[...]
>> But it can mean dealing with thousands of dollars to the exact cent --
>> and if you get a result of $1234.565001 and round it to $1234.57, when
>
> You cannot get a result of $1234.565... by only additive and subtractive
> transactions, such as recording expenses in a ledger whose
> denomination is pennies!

I didn't say otherwise.

[...]

--
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
Working, but not speaking, for Philips
void Void(void) { Void(); } /* The recursive call of the void */

Re: Can this program be improved?

<sqja15$ea4$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19680&group=comp.lang.c#19680

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: jameskuy...@alumni.caltech.edu (James Kuyper)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Wed, 29 Dec 2021 22:45:40 -0500
Organization: A noiseless patient Spider
Lines: 30
Message-ID: <sqja15$ea4$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<sqid71$bnf$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit
Injection-Date: Thu, 30 Dec 2021 03:45:41 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="4402dcb5329d2117b276a466d96fae67";
logging-data="14660"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/YaYC+an1dQS1rZOH4BStmsO3s1NkoaUs="
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101
Thunderbird/78.14.0
Cancel-Lock: sha1:PUyFyJmUS5CBSaQb+DQnYRRM390=
In-Reply-To: <sqid71$bnf$1@dont-email.me>
Content-Language: en-US
 by: James Kuyper - Thu, 30 Dec 2021 03:45 UTC

On 12/29/21 2:33 PM, Andrey Tarasevich wrote:
> On 12/29/2021 9:49 AM, Bart wrote:
....
>> It's not obvious that C's /default/ float type is 'double', nor that
>> 'float' is not the default float type, despite the name!
>
> It doesn't have to be obvious. That's why I state it explicitly.

Stating it explicitly is not as good as providing relevant citations.

That was certainly true in K&R C, where the usual arithmetic conversions
always caused float operands to be converted to double, and the default
argument promotions caused float arguments to be promoted to double.
However, in C90 the usual arithmetic conversions were changed so that
floating-point operands were never converted to a higher precision
unless the other operand had a higher precision.
In C90, none of the standard library functions took a float or long
double argument, but that changed in C99 - all of the math.h functions
now come in three different forms: one suffixed with 'f' that takes
float arguments and/or returns float values, one with no suffix for
double, and on suffixed with 'l' for long double.
C90 also introduced function prototypes. When calling a function with a
prototype declaration in scope (which is now the normal case), the
default argument promotions occur only for the variable parts of
variadic functions. That's the only sense in which "double is the
default" survived past C99.

I'd say that, since C99, it's far from obvious that double is the
default precision, and I'd say that the reason it's not obvious is
because it's no longer true.

Re: Can this program be improved?

<sqjr1g$jd5$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19682&group=comp.lang.c#19682

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: andreyta...@hotmail.com (Andrey Tarasevich)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Thu, 30 Dec 2021 00:35:59 -0800
Organization: A noiseless patient Spider
Lines: 13
Message-ID: <sqjr1g$jd5$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<sqid71$bnf$1@dont-email.me> <sqja15$ea4$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Thu, 30 Dec 2021 08:36:00 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="839fd59b56ae7f5555a3daa63d84a02a";
logging-data="19877"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18Do32y9eMkDY6YQrOnDsEU"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.4.1
Cancel-Lock: sha1:Y7IalGGKNih11cnDGeULi5gg7I0=
In-Reply-To: <sqja15$ea4$1@dont-email.me>
Content-Language: en-US
 by: Andrey Tarasevich - Thu, 30 Dec 2021 08:35 UTC

On 12/29/2021 7:45 PM, James Kuyper wrote:
>
> I'd say that, since C99, it's far from obvious that double is the
> default precision, and I'd say that the reason it's not obvious is
> because it's no longer true.

A rather obvious fact that an unsuffixed `0.0` is a `double` still
grants a significant degree of defaultness (sic) to `double`.

--
Best regards,
Andrey Tarasevich

Re: Can this program be improved?

<sqjtip$1km$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19683&group=comp.lang.c#19683

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: david.br...@hesbynett.no (David Brown)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Thu, 30 Dec 2021 10:19:20 +0100
Organization: A noiseless patient Spider
Lines: 22
Message-ID: <sqjtip$1km$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<sqid71$bnf$1@dont-email.me> <sqja15$ea4$1@dont-email.me>
<sqjr1g$jd5$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit
Injection-Date: Thu, 30 Dec 2021 09:19:21 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="7376c53bf237326f94440bc522260d18";
logging-data="1686"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+KqM9AdvtK1yDQCidPEahrM900KIBLvWs="
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101
Thunderbird/78.11.0
Cancel-Lock: sha1:euzrut/U11I7/nNuLh28h1gkHuI=
In-Reply-To: <sqjr1g$jd5$1@dont-email.me>
Content-Language: en-GB
 by: David Brown - Thu, 30 Dec 2021 09:19 UTC

On 30/12/2021 09:35, Andrey Tarasevich wrote:
> On 12/29/2021 7:45 PM, James Kuyper wrote:
>>
>> I'd say that, since C99, it's far from obvious that double is the
>> default precision, and I'd say that the reason it's not obvious is
>> because it's no longer true.
>
> A rather obvious fact that an unsuffixed `0.0` is a `double` still
> grants a significant degree of defaultness (sic) to `double`.
>

If you call a function for which there is no prototype (I think it is
insane that non-prototype declarations are still allowed in C, even C18,
but that's a side point) then any arguments of type "float" are promoted
to "double". The same applies to arguments to a function with a
variable number of arguments (in the ellipsis part).

That adds to the "double is default" argument (though I agree with James
that it is much less the default in C99 than it was in C90).

Re: Can this program be improved?

<164e3d93-e3f3-48b9-9399-b0352f02ff3dn@googlegroups.com>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19686&group=comp.lang.c#19686

  copy link   Newsgroups: comp.lang.c
X-Received: by 2002:ad4:5f89:: with SMTP id jp9mr27886634qvb.39.1640868530752;
Thu, 30 Dec 2021 04:48:50 -0800 (PST)
X-Received: by 2002:ac8:7dc1:: with SMTP id c1mr25736885qte.275.1640868530617;
Thu, 30 Dec 2021 04:48:50 -0800 (PST)
Path: i2pn2.org!i2pn.org!weretis.net!feeder6.news.weretis.net!news.misty.com!border2.nntp.dca1.giganews.com!border1.nntp.dca1.giganews.com!nntp.giganews.com!news-out.google.com!nntp.google.com!postnews.google.com!google-groups.googlegroups.com!not-for-mail
Newsgroups: comp.lang.c
Date: Thu, 30 Dec 2021 04:48:50 -0800 (PST)
In-Reply-To: <sqj0mf$532$1@dont-email.me>
Injection-Info: google-groups.googlegroups.com; posting-host=2a00:23a8:400a:5601:b18b:c237:288f:989e;
posting-account=Dz2zqgkAAADlK5MFu78bw3ab-BRFV4Qn
NNTP-Posting-Host: 2a00:23a8:400a:5601:b18b:c237:288f:989e
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com> <sqiprq$1kk$1@dont-email.me>
<87o84z2bsi.fsf@nosuchdomain.example.com> <sqj0mf$532$1@dont-email.me>
User-Agent: G2/1.0
MIME-Version: 1.0
Message-ID: <164e3d93-e3f3-48b9-9399-b0352f02ff3dn@googlegroups.com>
Subject: Re: Can this program be improved?
From: malcolm....@gmail.com (Malcolm McLean)
Injection-Date: Thu, 30 Dec 2021 12:48:50 +0000
Content-Type: text/plain; charset="UTF-8"
Lines: 13
 by: Malcolm McLean - Thu, 30 Dec 2021 12:48 UTC

On Thursday, 30 December 2021 at 01:06:35 UTC, Bart wrote:
>
> (In my country, tax returns only need figures in whole pounds, and don't
> need to be that exact. So long as you are not deliberately
> misrepresenting by significant amounts, it doesn't matter if they are a
> pound either way.)
>
In the UK, the Inland Revenue doesn't care about small amounts of money.

But, if you write a cheque to Inland Revenue, the amount the bank calculates
you have in your account needs to match the amount the program calculates
you have in your account to the exact penny. Not because accountants care
about one penny, but because any discrepancy, however small, could indicate
some more serious mis-accounting.

Re: Can this program be improved?

<sqk9tn$q5h$1@dont-email.me>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19687&group=comp.lang.c#19687

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: bc...@freeuk.com (Bart)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Thu, 30 Dec 2021 12:49:59 +0000
Organization: A noiseless patient Spider
Lines: 48
Message-ID: <sqk9tn$q5h$1@dont-email.me>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com> <sqiprq$1kk$1@dont-email.me>
<Cy6zJ.242630$IW4.143221@fx48.iad> <20211229162959.990@kylheku.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Thu, 30 Dec 2021 12:49:59 -0000 (UTC)
Injection-Info: reader02.eternal-september.org; posting-host="50a6f6e5a951aff34d7b2de53679ba6e";
logging-data="26801"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX198+VlWMKiBfU9AX76SbwushO7M9sTtLyI="
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.4.1
Cancel-Lock: sha1:xQfYWdTlfy2loev+nd9LXAFtLJI=
In-Reply-To: <20211229162959.990@kylheku.com>
 by: Bart - Thu, 30 Dec 2021 12:49 UTC

On 30/12/2021 00:34, Kaz Kylheku wrote:
> On 2021-12-29, Scott Lurndal <scott@slp53.sl.home> wrote:
>> Bart <bc@freeuk.com> writes:
>>> On 29/12/2021 22:37, Keith Thompson wrote:
>>>> Bart <bc@freeuk.com> writes:
>>>> [...]
>>>>> 3) Double is perfectly suitable for representing monetary amounts,
>>>>> especially in a toy program or for personal use. (I've used it for
>>>>> accounts within a small business.)
>>>>
>>>> In a toy program, sure -- and I'd say *only* in a toy program.
>>>>
>>>> Using floating-point for money risks, at best, rare off-by-one errors,
>>>> such as a computation yielding a result one cent off from the correct
>>>> value. I believe that would be considered unacceptable in any
>>>> real-world financial application.
>>>
>>> Real-world doesn't need to mean dealing with trillions of dollars to the
>>> exact cent.
>>
>> Real-world still uses COBOL for these type of applications.
>>
>>>
>>> Most businesses work with amounts far smaller. Then I believe the
>>> precision of float64 is enough to emulate the needed rounding methods.
>>
>> Why bother with the error-prone "needed rounding methods". Use uint64_t
>> and denominate in mills.
>
> This common intution is incorrect. Financial systems sometimews need to
> calculate fractional amounts, like a 15.03% tax or whatever.
>
> And in those situations, you may be required to implement the required
> rounding rules: what to do when some fractional result lands halfway
> between two pennies: which one does it go to.
>
> You cannot get away from rounding issues just because you used an
> integer representation for mills or penies.

The problem isn't the recommended rounding method, it's repeatability.

With floating point, an intermediate result might end in .4999999993 or
in .5000000007. If the rule is that up to exactly 0.5 rounds down, and
anything beyond rounds up, then it can go either way.

With integer divide, the results should be much more consistent: a
remainder will either be 4999999993 or 5000000007 or whatever, always.

Re: Can this program be improved?

<sqkphm$p3g$1@gioia.aioe.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=19691&group=comp.lang.c#19691

  copy link   Newsgroups: comp.lang.c
Path: i2pn2.org!i2pn.org!aioe.org!Puiiztk9lHEEQC0y3uUjRA.user.46.165.242.75.POSTED!not-for-mail
From: non...@add.invalid (Manfred)
Newsgroups: comp.lang.c
Subject: Re: Can this program be improved?
Date: Thu, 30 Dec 2021 18:16:38 +0100
Organization: Aioe.org NNTP Server
Message-ID: <sqkphm$p3g$1@gioia.aioe.org>
References: <sq63mi$gom$1@dont-email.me> <sq6b3t$ce5$1@dont-email.me>
<sqi3p9$1bia$1@gioia.aioe.org> <sqi72e$q7e$1@dont-email.me>
<87sfub2g2t.fsf@nosuchdomain.example.com> <sqiprq$1kk$1@dont-email.me>
<87o84z2bsi.fsf@nosuchdomain.example.com> <sqj0mf$532$1@dont-email.me>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Info: gioia.aioe.org; logging-data="25712"; posting-host="Puiiztk9lHEEQC0y3uUjRA.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Thunderbird/91.4.1
Content-Language: en-US
X-Notice: Filtered by postfilter v. 0.9.2
 by: Manfred - Thu, 30 Dec 2021 17:16 UTC

On 12/30/2021 2:06 AM, Bart wrote:
> On 30/12/2021 00:09, Keith Thompson wrote:
>> Bart <bc@freeuk.com> writes:
>
>>> Real-world doesn't need to mean dealing with trillions of dollars to
>>> the exact cent.
>>
>> But it can mean dealing with thousands of dollars to the exact cent --
>> and if you get a result of $1234.565001 and round it to $1234.57, when
>> the rules call for a result of $1234.56, that could be a serious problem.
>
> With floating point, that result could as easily be just under 1234.565
> as just over. If the requirements really are that binary floating point
> must have exactly identical results, down to the least significant bit,
> even for intermediates so that rounding will always give the same
> results too, then that's what you have to do.

Yes, and that's why standard floating point is not suitable for accurate
accounting.

IEEE 754 floating point types are designed for applications where its is
OK to assume that all values are approximated, e.g. measurements of
physical quantities. In this kind of environment the goal is to have
lots of decimal digits and huge scale of representation, some
predictable estimate of the propagation of rounding errors, and
calculation efficiency.
The price of not being able to represent exactly the value 1% (i.e.
0.01) is acceptable, even if this value is so common, as long as the
goals above are achieved.

The financial world has different requirements: they want exact results
whenever possible, and rounding errors, when impossible to avoid, are
thoroughly regulated.
This is because balancing the books down to the exact cent is important
to those guys.
In order to achieve this, they are willing to pay some price in terms of
representable numbers: the whole world uses monetary amounts quantified
down to the cent (2 decimal digits). In a similar fashion, conversion
ratios like currency exchange rates are conventionally expressed in a
fixed amount of significant digits (I think it's 6 or 7 digits), and the
same is likely to hold for interest rates as well. There's some upper
limit to the largest monetary amount to handle (e.g. the global wealth),
and so on.
Finally, calculations need not be super fast: a monetary transaction
involves much less computation than, say, modeling a magnetic field.

All in all, it's no surprise that the financial world uses different
data types than floating point, like e.g. the Decimal type.

Pages:12345
server_pubkey.txt

rocksolid light 0.9.8
clearnet tor