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
26 2573
Schizoid Man said: 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) ,
You reckon? :-)
whereas Excel is computing these large numbers quite easily. Any suggestions?
It isn't C that's blowing up. It's your program that's blowing up.
When you're dealing with huge numbers, you have to box clever. The Excel
programmers, it seems, have done so, and you have to do that too.
Let's take a smaller example than C(350,170). Say, C(15,5).
Using your method, the first thing you calculate is 15!, which is
1307674368000, which is way too big to fit into a 32-bit integer.
But you don't have to do it like that.
C(15,5) = 15! / ((15-5)! * 5!), which is 15! / (10! * 5!)
Let's write this out in full:
15*14*13*12*11* 10*9*8*7*6*5*4* 3*2*1
-----------------------------------
10*9*8*7*6*5*4* 3*2*1 * 5*4*3*2*1
Cancel 10!, leaving:
15*14*13*12*11
--------------
5*4*3*2*1
Cancel 15s:
14*13*12*11
--------------
4*2*1
Cancel 4s:
14*13*3*11
--------------
2*1
Cancel 2s:
7*13*3*11
This comes to 3003, which is easily within the range of int, and we got
there without having to over-burden any ints with colossal out-of-range
numbers.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999 http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Richard Heathfield wrote: Schizoid Man said:
This comes to 3003, which is easily within the range of int, and we got there without having to over-burden any ints with colossal out-of-range numbers.
Hi Richard,
Absolutely right - it's my program that's blowing up. I am evaluation
C(n,r) as n*(n-1)*...*(n-r+1) / r!
However, it seems that even the above expression could use a lot of
optimization.
Thanks for the input.
Schizoid Man wrote: 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?
I suspect that you have misidentified your problem. It's impossible to
tell, since you have not given us compilable code that exhibits your
problem. Try the following, and tell us what happens:
#include <stdio.h>
int main(void)
{
double t = 0.1;
int steps = 10;
double time_step = t / /* unnecessary (double) */ steps;
printf("%5.5f\n ", time_step);
return 0;
}
When I run the code above, I get:
0.01000
What do you get?
Richard Heathfield wrote: Schizoid Man said: 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.
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) ,
You reckon? :-)
whereas Excel is computing these large numbers quite easily. Any suggestions?
It isn't C that's blowing up. It's your program that's blowing up.
When you're dealing with huge numbers, you have to box clever. The Excel programmers, it seems, have done so, and you have to do that too.
Let's take a smaller example than C(350,170). Say, C(15,5).
Using your method, the first thing you calculate is 15!, which is 1307674368000, which is way too big to fit into a 32-bit integer.
But you don't have to do it like that.
C(15,5) = 15! / ((15-5)! * 5!), which is 15! / (10! * 5!)
Let's write this out in full:
15*14*13*12*11* 10*9*8*7*6*5*4* 3*2*1 ----------------------------------- 10*9*8*7*6*5*4* 3*2*1 * 5*4*3*2*1
Cancel 10!, leaving:
15*14*13*12*11 -------------- 5*4*3*2*1
Cancel 15s:
14*13*12*11 -------------- 4*2*1
Cancel 4s:
14*13*3*11 -------------- 2*1
Cancel 2s:
7*13*3*11
This comes to 3003, which is easily within the range of int, and we got there without having to over-burden any ints with colossal out-of-range numbers.
As an example of extending usable ranges, especially for
factorials, here is something I cooked up a few years ago:
/* compute factorials, extended range
on a 32 bit machine this can reach fact(15) without
unusual output formats. With the prime table shown
overflow occurs at 101.
Public domain, by C.B. Falconer. 2003-06-22
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/* 2 and 5 are handled separately
Placing 2 at the end attempts to preserve such factors
for use with the 5 factor and exponential notation
*/
static unsigned char primes[] = {3,7,11,13,17,1 9,23,29,31,37,
41,43,47,53,57, 59,61,67,71,
/* add further primes here -->*/
2,5,0};
static unsigned int primect[sizeof primes]; /* = {0} */
static double fltfact = 1.0;
static
unsigned long int fact(unsigned int n, unsigned int *zeroes)
{
unsigned long val;
unsigned int i, j, k;
#define OFLOW ((ULONG_MAX / j) < val)
/* This is a crude mechanism for passing back values */
for (i = 0; i < sizeof primes; i++) primect[i] = 0;
for (i = 1, val = 1UL, *zeroes = 0; i <= n; i++) {
fltfact *= i; /* approximation */
j = i;
/* extract exponent of 10 */
while ((0 == (j % 5)) && (!(val & 1))) {
j /= 5; val /= 2;
(*zeroes)++;
}
/* Now try to avoid any overflows */
k = 0;
while (primes[k] && OFLOW) {
/* remove factors primes[k] */
while (0 == (val % primes[k]) && OFLOW) {
val /= primes[k];
++primect[k];
}
while (0 == (j % primes[k]) && OFLOW) {
j /= primes[k];
++primect[k];
}
k++;
}
/* Did we succeed in the avoidance */
if (OFLOW) {
#if DEBUG
fprintf(stderr, "Overflow at %u, %lue%u * %u\n",
i, val, *zeroes, j);
#endif
val = 0;
break;
}
val *= j;
}
return val;
} /* fact */
int main(int argc, char *argv[])
{
unsigned int x, zeroes;
unsigned long f;
if ((2 == argc) && (1 == sscanf(argv[1], "%u", &x))) {
if (!(f = fact(x, &zeroes))) {
fputs("Overflow \n", stderr);
return EXIT_FAILURE;
}
printf("Factori al(%u) == %lu", x, f);
if (zeroes) printf("e%u", zeroes);
for (x = 0; primes[x]; x++) {
if (primect[x]) {
printf(" * pow(%d,%d)", primes[x], primect[x]);
}
}
putchar('\n');
printf("or approximately %.0f.\n", fltfact);
return 0;
}
fputs("Usage: fact n\n", stderr);
return EXIT_FAILURE;
} /* main */
--
Some informative links:
news:news.annou nce.newusers http://www.geocities.com/nnqweb/ http://www.catb.org/~esr/faqs/smart-questions.html http://www.caliburn.nl/topposting.html http://www.netmeister.org/news/learn2quote.html
CBFalconer wrote: As an example of extending usable ranges, especially for factorials, here is something I cooked up a few years ago:
Thank you very much for the example. You're absolutely right about
non-standard libraries and methods, but I just want to get up and
running with C in time for this interview.
I'm having another odd problem. In the following funcation, I am trying
to dimension an array declaration using a value that is passed to the
function.
double treeNPV(int steps) {
const int array_dim = steps;
double s_price[array_dim][array_dim];
}
However, I get the following compile errors:
- cannot allocate an array of constant size 0
- expected constant expression
The code looks correct. Or am I missing something very basic again?
Thank you.
Schizoid Man wrote: CBFalconer wrote: As an example of extending usable ranges, especially for factorials, here is something I cooked up a few years ago: Thank you very much for the example. You're absolutely right about non-standard libraries and methods, but I just want to get up and running with C in time for this interview.
Have you read the C FAQ yet? I would strongly recommend that you do so
and try to inderstand as much as possible before your interview, it is
available at <http://c-faq.com/>.
I'm having another odd problem. In the following funcation, I am trying to dimension an array declaration using a value that is passed to the function.
double treeNPV(int steps) {
const int array_dim = steps; double s_price[array_dim][array_dim];
}
However, I get the following compile errors: - cannot allocate an array of constant size 0 - expected constant expression
The code looks correct. Or am I missing something very basic again?
Prior to C99 the size of an array had to be specified using an integer
constant expression (sometimes referred to as ICE). Despite
appearances, a "const" qualified type is not a constant expression in
C, see FAQ question 11.8. C99 introduced variable length arrays (VLAs)
removing the constant expression requirement, your compiler apparently
doesn't support them (or at least not in the mode in which you are
invoking it). In any case, arrays in C must have a size greater than 0
so you should validate array_dim before using it to declare s_price.
Robert Gamble
Robert Gamble wrote: Schizoid Man wrote:
Have you read the C FAQ yet? I would strongly recommend that you do so and try to inderstand as much as possible before your interview, it is available at <http://c-faq.com/>.
Hi Robert,
I'll take a look at it. Probably more useful that inundating this forum.
It's not a programming job, though the interview will test some computer
science and I believe C is the language of choice. Unfortunately, I am
an Excel/VBA/VB monkey at work, so my C is rusty at best.
Thank you for the suggestion.
this is the simple program sohwin u r problem
but i go the correct answer....
#include<stdio. h>
int main()
{
double t = 0.1;
int steps = 10;
double time_step = t / (double)steps;
printf("%5.5f\n ", time_step);
return 0;
}
the output of this prog is 0.01000
In article <e5**********@g eraldo.cc.utexa s.edu>,
Schizoid Man <sc***@sf.com > wrote: scanf_s is a method that replaces scanf in the new Visual C++, scanf has been deprecated. Similarly, for the tchar.h file too.
Microsoft can "deprecate" whatever it likes, if but you follow them
you will restrict your code to Microsoft operating systems.
-- Richard This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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!
|
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);
|
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...
|
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)...
|
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...
| |
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...
|
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...
|
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>
|
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...
|
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
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |