473,763 Members | 9,275 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Arithmetic problem

Hi,

I have a very strange arithmetic problem in C:

double t = 0.1;
int steps = 10;
double time_step = t / (double)steps;

I would expect the output of time_step to be 0.01000 (my output is of
the form %5.5f), but instead it a very large (and incorrect) negative
number.

Any ideas?

Thanks,
Schiz
Jun 3 '06 #1
26 2572
In article <e5**********@g eraldo.cc.utexa s.edu>,
Schizoid Man <sc***@sf.com > wrote:
I have a very strange arithmetic problem in C:


Show us a complete program that has the problem.

-- Richard
Jun 3 '06 #2
Richard Tobin wrote:
Show us a complete program that has the problem.


Hi Richard,

Here's the complete program. Thank you.

(This is the problematic module - any of the values passed to this
function apart from steps, returns a very odd number)

#include "stdafx.h"
#include "binomialtree.h "

double treeNPV(double s, double k, double r, double v, double t, int steps)
{
double time_step, up, dn, rt, p, npv;
time_step = t / (double)(steps) ;
rt = exp(r*time_step );
up = exp(v*sqrt(time _step));
dn = 1/up;
p = (rt-dn)/(up-dn);

npv = 0.0;

//for (int i=0; i<=steps; i++)
npv = v;

return npv;
}

Main modules:

#include "stdafx.h"
#include "binomialtree.h "

int main(void)
{
double s, k, r, v, t;
double call_npv;
int steps;
printf("Enter asset price S: ");
scanf_s("%f", &s);
printf("Enter strike price K: ");
scanf_s("%f", &k);
printf("Enter riskfree rate R: ");
scanf_s("%f", &r);
printf("Enter volatility V: ");
scanf_s("%f", &v);
printf("Enter time to expiry T: ");
scanf_s("%f", &t);
printf("Enter number of steps: ");
scanf_s("%d", &steps);
call_npv = treeNPV(s,k,r,v ,t,steps);
printf("Call option NPV is: %5.5f", call_npv);
scanf_s("%d", &steps);
return 0;
}

Header files:

// stdafx.h : include file for standard system include files,

#pragma once
#define WIN32_LEAN_AND_ MEAN // Exclude rarely-used stuff from Windows
headers
#include <stdio.h>
#include <tchar.h>

// binomialtree.h
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define pi 3.1415926535897 93238

double treeNPV(double s, double k, double r, double v, double t, int steps);
Jun 3 '06 #3
In article <e5**********@g eraldo.cc.utexa s.edu>,
Schizoid Man <sc***@sf.com > wrote:
Here's the complete program. Thank you. scanf_s("%f", &s);
I don't know what scanf_s is. It's not a standard C function.
#include <tchar.h>


And I don't know what tchar.h is.

But if scanf_s is like scanf, then you should be using format %lf
to read into a double.

-- Richard
Jun 4 '06 #4
Schizoid Man wrote:
Richard Tobin wrote:
Show us a complete program that has the problem.


Hi Richard,

Here's the complete program. Thank you.

(This is the problematic module - any of the values passed to this
function apart from steps, returns a very odd number)

#include "stdafx.h"
#include "binomialtree.h "

double treeNPV(double s, double k, double r, double v, double t, int steps)
{
double time_step, up, dn, rt, p, npv;
time_step = t / (double)(steps) ;
rt = exp(r*time_step );
up = exp(v*sqrt(time _step));
dn = 1/up;
p = (rt-dn)/(up-dn);

npv = 0.0;

//for (int i=0; i<=steps; i++)
npv = v;

return npv;
}

Main modules:

#include "stdafx.h"
#include "binomialtree.h "

int main(void)
{
double s, k, r, v, t;
double call_npv;
int steps;
printf("Enter asset price S: ");
scanf_s("%f", &s);


for "double", you may need to use %lf

scanf_s("%lf", &s);

Anyway, dont know what's scanf_s() in your code. there might have some
strange behaviers for some implementations by using scanf() statements
to accept inputs. but if scanf_s() is your self-defined function using
something like fget() and sscanf(), that should be OK:)..

BTW, what's the values of "steps" before and after you enter the
subroutine treeNPV(). gdb is always your friend to check this info. :-)

Xicheng

Jun 4 '06 #5
Richard Tobin wrote:
And I don't know what tchar.h is.

But if scanf_s is like scanf, then you should be using format %lf
to read into a double.


Hi Richard,

Absolutely right. %lf did the trick. I'm looking at C after ages - I
have a job interview coming up! :)

scanf_s is a method that replaces scanf in the new Visual C++, scanf has
been deprecated. Similarly, for the tchar.h file too.

On another note, can you tell me why the following method are not giving
me Combination results over 12? The following program works fine till 12
and then mysteriously blows up.

unsigned long int factorial(int x) {
if (x==0)
return 1;
else {
unsigned int y;
y = x;
for (int i=x-1; i>=1; i--)
y=y*i;
return y;
}
}

unsigned long int combin(int n, int r) {
if (r==0 || r==n)
return 1;
if (r==1 || r==n-1)
return n;
if (r>1 && r<n)
return factorial(n)/(factorial(r)*f actorial(n-r));
}
Jun 4 '06 #6
Richard Tobin wrote:
In article <e5**********@g eraldo.cc.utexa s.edu>,
Schizoid Man <sc***@sf.com > wrote:
Here's the complete program. Thank you.
scanf_s("%f", &s);


I don't know what scanf_s is.


This is part of a Microsoft initiative to make parts of the C library
"safer". There is now a Technical Report dedicated to this initiative
in the hopes of making it Standard some day. Check out
http://www.open-std.org/jtc1/sc22/wg...docs/n1146.pdf for the ugly
details. It is, IMNSHO, completely ass-backwards.
It's not a standard C function.


Let's hope it stays that way.

Robert Gamble

Jun 4 '06 #7
Op Sat, 03 Jun 2006 18:01:37 -0700 schreef Schizoid Man:
Richard Tobin wrote:
And I don't know what tchar.h is.

But if scanf_s is like scanf, then you should be using format %lf
to read into a double.


Hi Richard,

Absolutely right. %lf did the trick. I'm looking at C after ages - I
have a job interview coming up! :)

scanf_s is a method that replaces scanf in the new Visual C++, scanf has
been deprecated. Similarly, for the tchar.h file too.

On another note, can you tell me why the following method are not giving
me Combination results over 12? The following program works fine till 12
and then mysteriously blows up.


12 factorial can fit in 32 bits. 13 factorial won't.
--
Coos
Jun 4 '06 #8
Schizoid Man wrote:
On another note, can you tell me why the following method are not giving
me Combination results over 12? The following program works fine till 12
and then mysteriously blows up.


Actually, not so mysterious after all - the unsigned int was the
culprit. Replacing that with a long double does the trick.

Thanks.
Jun 4 '06 #9
Coos Haak wrote:
On another note, can you tell me why the following method are not giving
me Combination results over 12? The following program works fine till 12
and then mysteriously blows up.


12 factorial can fit in 32 bits. 13 factorial won't.


Hi Coos,

I figured that out, albeit after I posted my message.

The function I'm trying to evaluate is Combin(n,r) = factorial(n) /
(factorial (n-r) * factorial (r)).

For some reason, C is blowing up for numbers like Combin(350,170) ,
whereas Excel is computing these large numbers quite easily. Any
suggestions?

Thanks.
Jun 4 '06 #10

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

Similar topics

14
2637
by: Amit Bhatia | last post by:
Hi there. I am cross posting this on comp.lang.c as well: sorry for same. The problem I am facing is as follows: For example: double a= 0.15; double b=2.4; const double VERYTINY =1.e-10; I know b/a = 16 and hence the remainder is zero; but I am not able to find any suitable thing to encode it into in c. for example (fmod(b,a)>VERYTINY) returns true!
6
7237
by: Pushkar Pradhan | last post by:
I tried to read the archives and solve this problem, but now I think I better post my problem: int main() { int blkSz = { {2,2}, {2,3}, ....., {6,6} }; write_bc_perf(mflops1, blkSz, NUMBASECASES);
10
2271
by: Shawn | last post by:
Hello all, I apologize as I am sure this has probably been dealth with before... but I am doing an exercise from "Practical C Programming" and I have been unable to get it to work perfectly due to problems with floating point arithmetic and I am looking for a way to solve it. See the code below... Given a certain amount of change (below $1.00) the program will tell you how many of each coin you will need to get that amount. The program...
16
5137
by: TTroy | last post by:
Hello, I'm relatively new to C and have gone through more than 4 books on it. None mentioned anything about integral promotion, arithmetic conversion, value preserving and unsigned preserving. And K&R2 mentions "signed extension" everywhere. Reading some old clc posts, I've beginning to realize that these books are over-generalizing the topic. I am just wondering what the difference between the following pairs of terms are: 1)...
4
1555
by: PDHB | last post by:
I'm sorry, but this is just the height of stupidity. I love the dot net framework. It has actually been sufficient to convert an anti-microsoft extremist (myself) to the windows camp. But not having numerical value types inherit from an interface to allow for arithmetic in generics, or in some other way allow arithmetic in generics without a performance killing or ugly work around is just the epitomy of idiocy. Yes, microsoft today is...
4
4147
by: Tom | last post by:
I have a VB.NET framework 1.1 application that I am installing on my user's workstation. It works fine on EVERY machine except for one - on this one machine it generates a 'Overflow or underflow in the arithmetic operation' when I attempt to instantiate my first form, as so: Dim frm As New frmMyForm() Based on some things I saw here, I thought it might be that this workstation didn't have a MS Sans Seriff font on it (since that is the...
26
3062
by: Bill Reid | last post by:
Bear with me, as I am not a "professional" programmer, but I was working on part of program that reads parts of four text files into a buffer which I re-allocate the size as I read each file. I read some of the items from the bottom up of the buffer, and some from the top down, moving the bottom items back to the new re-allocated bottom on every file read. Then when I've read all four files, I sort the top and bottom items separately...
5
555
by: jdcrief | last post by:
I have all of this program working except for the pointer arithmetic part, I think. This program should average the student's grades together using pointer arithmetic and then display the student's and their average grade. I do know that I will need to delete the array to avoid a memory leak, but I am stuck on this part of the program. I am open to any suggestions. #include "stdafx.h" #include <iostream> #include <stdio.h>
1
6230
by: mmm | last post by:
I wrote the code below to create simple arithmetic sequences that are iter-able I.e., this would basically combine the NUMPY arange(start,end,step) to range(start,end), with step not necessarily an integer. The code below is in its simplest form and I want to generalize the sequence types (multiplicative, cumulative, gauss ...), but first I need the simple SEQA( ) function to be more robust. The problem is the three test code...
5
2624
by: Selvam | last post by:
Hi All, I am getting exponent value when doing float arithmetic in C++. Instead of that I need accurate value. float amount = 0.0f; float x = 0.99999976f; amount= 1.0f - x; I am getting amount as 2.3841858e-007 instead of 0.00000024
0
9564
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
9387
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10148
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
10002
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
9938
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
9823
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6643
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
5270
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...
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.