james_womack
james_womack

Reputation: 10296

Converting academic mathematical notation to C code

Those of you that are even moderately knowledgable of math will likely laugh, but I don't remember what much of the notation rules in math and I need assistance converting this into C code. Your help is greatly appreciated:

                                         214
          10,000 {(10,000 × [1+.0599/365]   )} +300
answer = ────────────────────────────────────────────
                                   214
                     .1+(1+(i/365))

Upvotes: 0

Views: 659

Answers (4)

Martin Beckett
Martin Beckett

Reputation: 96109

Simple - just a couple of common mistakes to watch for.

Put a .0 after the constant numbers (especially in the denominator) so that 'c' treats the calculation as floating point math rather than integer.
In 'C' 100/1000 is 0 100/1000.0 is 0.1

Use brackets liberally- don't trust remembering the precedence rules.

You need to use * everywhere for multiplication 3(1+2) is not a multiplication.

The pow(x,y) function is used for x^y. Modern C++ compilers have optimized versions where y is an integer, so x^2 is much faster than x^2.0

Upvotes: 2

Mike Axiak
Mike Axiak

Reputation: 11994

Are you looking for a program to translate that for you, or just a one-off conversion? If it's just a one off conversion, it's not that exciting.

Assuming I've read your syntax correctly:

double ans = 10000 * (10000 * pow(1.0 + 0.0599 / 365, 214) + 300;
ans /= (0.1 + pow(1.0 + (i / 365.0), 214));

I will say, though, that you may have an issue with raising things to that high of an exponent and dividing. More likely you will have to translate to logs and do your math in the log space, and convert afterwards.

What that might look like:

double lognumerator = log(10000) + log(10000) + 214 * log(1 + 0.0599 / 365);
double logdenominator = log(0.1 + exp(214 * log(1.0 + (i / 365.0))));
double ans = exp(lognumerator - logdenominator) + exp(log(300) - logdenominator);

The use of log may prevent you from hitting underflow, which you may very well hit with these types of computations.

Upvotes: 12

Starkey
Starkey

Reputation: 9781

(10000.0 ( ( 10000.0 * pow(1 + 0.0599/365.0, 214.0))) + 300.0 ) / (1 + pow(1 + i/365.0, 214.0))

I think I got that right. :)

Upvotes: 0

Gangadhar
Gangadhar

Reputation: 1903

Are you looking for the pow(x,y) function to calculate the power ?

Upvotes: 0

Related Questions