473,795 Members | 2,967 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using a math function in C.

Here is some code. I am trying to figure out how to raise, say, x to
the yth power. I know that isn't explicitly what is in the code but
that is the idea I am trying to solve. See the 2nd for loop>>3 errors.

#include <stdio.h>
#include <math.h>

int main(void)
{
#define p 100000;
int j, k, t, s;
float i;
double m, a, r, q;

printf(" Mortgage Payment Plan");
printf("Princip le Interest Rate Duration Monthly Payment
Total Payment");

for(i=0.06; i<0.11; i+0.01)
{
for(t=5; t<35; t+5)
{
s = t*12;
r = (1/ (1+i/12));
q = pow(double r, int s);
m = (p*i/12) / (1-q);
a = m*t*12;
printf("%d %.2f %d %.2f %.2f", p, i, t, m, a);
}
}
return 0;
}

The style isn't very good. But, I just need to produce an output for
class. Hey, thanks for your help with this one. I appreciate it.
David
Nov 13 '05 #1
3 3446

"David" <df******@aol.c om> wrote in message
Here is some code. I am trying to figure out how to raise, say, x to
the yth power. I know that isn't explicitly what is in the code but
that is the idea I am trying to solve. See the 2nd for loop>>3 errors.

#include <stdio.h>
#include <math.h>

int main(void)
{
#define p 100000; This #define has a trailing semi-colon, which will cause problems.
Also, "p" isn't a particularly good label to #define int j, k, t, s;
float i;
double m, a, r, q;
We also have the problem here that the variables are all single letters, so
it is difficult to understand what they are used for.
printf(" Mortgage Payment Plan");
printf("Princip le Interest Rate Duration Monthly Payment
Total Payment");
You probably want newlines at the end of these printf()s.
for(i=0.06; i<0.11; i+0.01)
This is totally confusing. Why does i go from 0.06 to 0.11 in increments of
0.01? You need a comment.
You should also be aware that floating point arithemtic isn't exact. The
test i<0.11 might not compare false at the exact point you expect it to.
{
for(t=5; t<35; t+5)
{
s = t*12;
r = (1/ (1+i/12));
q = pow(double r, int s); This is a syntax error. You call a C function without the types.
q = pow(r, s);
Note that s will automatically be promoted to a double - pow() handles
non-integral powers.
A good exercise would be to speed it up by writing your own integerpow()
function. m = (p*i/12) / (1-q);
a = m*t*12;
printf("%d %.2f %d %.2f %.2f", p, i, t, m, a);
}
}
return 0;
}

The style isn't very good. But, I just need to produce an output for
class. Hey, thanks for your help with this one. I appreciate it.
David

Nov 13 '05 #2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,

David wrote:
Here is some code. I am trying to figure out how to raise, say, x to
the yth power. I know that isn't explicitly what is in the code but
that is the idea I am trying to solve. See the 2nd for loop>>3 errors.


A fast way to do so is:
x^y = z then
log(x^y) = log(z) then
y*log(x) = log(z)
You could use the math funcion "log" to solve the left logarithm (natural
logarithm), then use "exp" to raise the result to get 'z'.
For a "normal" way of doing it, look for "pow".

Note: log(base,number ) = log(2,number) / log(2,base), and working with powers
of two is much faster than with non-power ones.
- --
Juan Ángel
PGP key on pgp.rediris.es (8FAF18B7)
or search on http://www.rediris.es/cert/servicios/keyserver/

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.3 (GNU/Linux)

iD8DBQE/UOLCaQjbS4+vGLc RAtrzAKCC+BABlw 4hvjUZQQ7Ha0kip qO9BQCgjOeS
feR5OnYYA1yAerd 8or7ZlNA=
=BW9h
-----END PGP SIGNATURE-----
Nov 13 '05 #3
David wrote:
Here is some code. I am trying to figure out how to raise, say, x to
the yth power. I know that isn't explicitly what is in the code but
that is the idea I am trying to solve. See the 2nd for loop>>3 errors.
The problem with "raising x to the yth power" is this line, q = pow(double r, int s); This should simply be
q = pow(r,s);
Note that pow() takes two double arguments; the integer 's' will have its
value passed as a double, because the prototype for pow() in <math.h> tells
the compiler that the second argument needs to be promoted to a double.

I have preserved your code at EOM for anyone who missed your post and wants
to comment on it. Here is, I believe, a translation of your code in
somewhat more idiomatic C. Note that the BASICy single character names
that you use are obfuscating. If I erred in interpreting them, that is the
normal result of trying to read such code. You will see an attempt to make
your output table less susceptible to guessing what the output specifiers
will produce, a cleaner way to handle loops involving floating-point
quantities, replacement of floats with doubles, and, of course, correction
of the invocation of pow(). I neither guarantee that the logic -- which is
yours -- is correct nor assert that the program could not be further improved.

#include <stdio.h>
#include <math.h>

int main(void)
{
const double principle = 100000.;
int years, months;
double nominalrate;
double monthypayment, totalpayment, monthlyrate, actualrate;
int irate;

printf("%-10s %-7s %-5s %-9s\n", "", "Mortgage", "Payment",
"Plan");
printf("%-10s %-7s %-5s %-9s %-15s %-15s\n", "Principle" ,
"Interest", "Rate", "Duration", "Monthly Payment",
"Total Payment");

for (irate = 6; irate < 11; irate++) {
nominalrate = irate / 100.;
for (years = 5; years < 35; years += 5) {
months = years * 12;
monthlyrate = (1 / (1 + nominalrate / 12));
actualrate = pow(monthlyrate , months);
monthypayment =
(principle * nominalrate / 12) / (1 - actualrate);
totalpayment = monthypayment * years * 12;
printf("%10.0f %7.2f %5d %9d %15.2f %15.2f\n",
principle, nominalrate, 12, years,
monthypayment, totalpayment);
}
}
return 0;
}

[David's code]
#include <stdio.h>
#include <math.h>

int main(void)
{
#define p 100000;
int j, k, t, s;
float i;
double m, a, r, q;

printf(" Mortgage Payment Plan");
printf("Princip le Interest Rate Duration Monthly Payment
Total Payment");

for(i=0.06; i<0.11; i+0.01)
{
for(t=5; t<35; t+5)
{
s = t*12;
r = (1/ (1+i/12));
q = pow(double r, int s);
m = (p*i/12) / (1-q);
a = m*t*12;
printf("%d %.2f %d %.2f %.2f", p, i, t, m, a);
}
}
return 0;
}

The style isn't very good. But, I just need to produce an output for
class. Hey, thanks for your help with this one. I appreciate it.
David


--
Martin Ambuhl

Nov 13 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
4662
by: Brian Richmond | last post by:
I'm trying to use a regular expression to match a hidden html tag and replace it with the results of a mysql query. The query is based off a part of the hidden tag. For example: The article looks like this ("Math" is the value I want to pass to my function call, it could be any value for the department name): $article = "Below is a listing of the staff in our Math department:<p><!-- Directory:Math -->"; I'm using this preg_replace...
17
3629
by: cwdjrxyz | last post by:
Javascript has a very small math function list. However there is no reason that this list can not be extended greatly. Speed is not an issue, unless you nest complicated calculations several levels deep. In that case you need much more ram than a PC has to store functions calculated in loops so that you do not have to recalculate every time you cycle through the nest of loops. Using a HD for storage to extend ram is much too slow for many...
11
14897
by: srinivas | last post by:
Hi all, I have one requirement.Is there any way to create a line graph using javascript.If it is please send me the sample code.But the thing is it should work in all browsers. Thanks, Srinivas
7
2453
by: bravesplace | last post by:
Hello, I am using the folling funtion to round a number to a single digit on my form: function round1(num) { return Math.round(num*1)/1 }
2
3327
by: ChrisO | last post by:
I've been pretty infatuated with JSON for some time now since "discovering" it a while back. (It's been there all along in JavaScript, but it was just never "noticed" or used by most until recently -- or maybe I should just speak for myself.) The fact that JSON is more elegant goes without saying, yet I can't seem to find a way to use JSON the way I *really* want to use it: to create objects that can be instantated into multiple...
2
2468
by: davidson1 | last post by:
Hai friends..for menu to use in my website..i found in one website....pl look below website.... http://www.dynamicdrive.com/dynamicindex1/omnislide/index.htm i downloaded 2 files.... menuitems.js mmenu.js
0
1958
by: Akira Kitada | last post by:
Hi Marc-Andre, Thanks for the suggestion. I opened a ticket for this issue: http://bugs.python.org/issue4204 Now I understand the state of the multiprocessing module, but it's too bad to see math, mmap and readline modules, that worked fine before, cannot be built anymore.
17
3927
by: Lenni | last post by:
Hi, I'm currently writing a web application for bicycle wheel builders that calculate the spoke length for all sorts of variations of hubs and rims. I have translated the formula from an Excel spreadsheet and in JavaScript it looks like this: var sll=Math.sqrt(Math.pow(((fdl/2*Math.sin((2*Math.PI*cross)))/
0
1818
by: M.-A. Lemburg | last post by:
On 2008-10-25 20:19, Akira Kitada wrote: Thanks. The errors you are getting appear to be related to either some missing header files or a missing symbol definition to enable these - looking at the ticket, you seem to have resolved all this already :-)
1
3464
by: swethak | last post by:
hi, i have a code to disply the calendar and add events to that. It works fine.But my requirement is to i have to disply a weekly and daily calendar.Any body plz suggest that what modifications i have to made in my code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type"...
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10436
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10213
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10163
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9040
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3722
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.