473,651 Members | 2,787 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem regarding sum of digits of floating point number in C

hi there,

recently i have got a problem regarding calculation of sum of digits in
a floating point or precision number. the weird behaviour of
compiler/language is preventing me from calculating the sum of all
digits. the compiler doesnt store the number as given by the user. some
of the precision digits are lost or changed (at will!). so by any
method, i m unable to reliably calculate the sum of provided number;
except i input the number as a string!

i have tried 2 types of logic -

first i use the intuitive logic of multiplying by 10 and adding the
integer part to the 'sum' in each iteration. all goes well until final
precision digit where this final digit is expanded. e.g. if 0.7 is
remaining, it is expanded to 0.69999999998! why dear, why r u doing
those things that we don want u to do?
/*************** *************** *************** ******/
width=strlen(lt oa((int)a,0,10) );
sprintf(str,"%* .*f",width,MAXL EN-width,a);
do{
if(*s=='.') // ignore '.'
continue;
if(!isdigit(*s) ) //we have got a char in num, so break away!
break;
else sum+=*s-0x30; //convert to digit from ASCII
}while(*++s);
/*************** *************** *************** ******/
in this case, the sprintf truncates or even expands(reverse of
rounding) long precision numbers.

even the good old gcc is truncating the precision digits at will.

this problem proved to be harder than what i thought initially.

any suggestions?

btw, sorry for this long post, but i m hurt u know? ;-)
TIA
Shreyas Kulkarni

Nov 14 '05 #1
1 3868
Shreyas Kulkarni wrote:
hi there,

recently i have got a problem regarding calculation of sum of digits in
a floating point or precision number. the weird behaviour of
compiler/language is preventing me from calculating the sum of all
digits. the compiler doesnt store the number as given by the user. some
of the precision digits are lost or changed (at will!). so by any
method, i m unable to reliably calculate the sum of provided number;
except i input the number as a string!

i have tried 2 types of logic -

first i use the intuitive logic of multiplying by 10 and adding the
integer part to the 'sum' in each iteration. all goes well until final
precision digit where this final digit is expanded. e.g. if 0.7 is
remaining, it is expanded to 0.69999999998! why dear, why r u doing
those things that we don want u to do?
/*************** *************** *************** ******/
width=strlen(lt oa((int)a,0,10) );
sprintf(str,"%* .*f",width,MAXL EN-width,a);
do{
if(*s=='.') // ignore '.'
continue;
if(!isdigit(*s) ) //we have got a char in num, so break away!
break;
else sum+=*s-0x30; //convert to digit from ASCII
}while(*++s);
/*************** *************** *************** ******/
in this case, the sprintf truncates or even expands(reverse of
rounding) long precision numbers.

even the good old gcc is truncating the precision digits at will.

this problem proved to be harder than what i thought initially.

any suggestions?

btw, sorry for this long post, but i m hurt u know? ;-)
TIA
Shreyas Kulkarni


You need a course in computer arithmetic!

Floats are generally represented using the IEEE standard #754.
http://en.wikipedia.org/wiki/IEEE_fl...point_standard
as 32 bits, 64 bits. Bog standard Intel x86 CPUs do all their floating point
arithmetic using the IEEE representation in hardware.

But this is base 2, and when you convert to/from base 10 rounding errors
occur and you get the errors you see.

Single precision (float in C) has about 6 to 7 significant digits; double
precision (double in C) has about 15 significant digits.

You can try
- using double instead of float
- using double, and rounding to say 10 significant digits.

gtoomey
Nov 14 '05 #2

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

Similar topics

3
2538
by: mg | last post by:
Hi everybody... We try to white scripts with Pyrhon 2.4 for an acoustic simulation and we wrote these follow lines : <begin script> c = 340 i =j=k= 1 sum_ = 23 table =
5
2685
by: towers | last post by:
Hello, I've got a bit of experience in C++, but I'm writing my first app that is dependent on relatively precise math functions. The app requires that I get a time stamp based on s sample number, from a time series. This seems liek an easy thing to do: long lSample = 500; (for example) double dSampleRate = 1000.0;
21
12675
by: syntax | last post by:
hi, i need to get high presion float numbers. say, i need pi = 22/7.0 = 3.142857....(upto 80 digits) is it possible ? does gcc/g++ compiler can give such type of high precision?? plz GIVE A SMALL CODE HOW CAN I ACHIEVE THAT ? which way, i have to
11
434
by: gouqizi.lvcha | last post by:
Hi all I have a large vector with float point numbers in it, for example (1.1, 2.1 , 3.2 , 3.3 , 4, 6, 3.2, 8). Is there an easy way to determine how many uique elements in the array? Thanks Rick
7
1966
by: Hiten | last post by:
Hi please check ffollowing conditon variable float1 and float2 holds user entered value..... Answer=float1 * float2; //output must be 8.5 output must to be 8.5 but it has 8.500002, i am confused at this point i used calculators and other calculation mathods to see the actual value and thet give correct 8.5 with no other decimals......
16
1879
by: Guenther Sohler | last post by:
I have following code: int main(void) { printf("%.3lf\n",-2158470*0.001); } it prints -2158.470
14
3066
by: chun ping wang | last post by:
Hey i have a stupid question. How do i get python to print the result in only three decimal place... Example>>> round (2.995423333545555, 3) 2.9950000000000001 but i want to get rid of all trailing 0's..how would i do that? _________________________________________________________________
2
3472
by: Mukesh_Singh_Nick | last post by:
What is meant by the "most significant digits" in the following statement? <BLOCKQUOTE> With %g and %G, the precision modifier determines the maximum number of significant digits displayed.</BLOCKQUOTE> The statement appears here: http://www.cppreference.com/stdio/printf.html Also, what do we mean by the magnitude of a floating point number?
11
2060
by: Peter | last post by:
I have written this small app to explain an issue I'm having with a larger program. In the following code I'm taking 10 ints from the keyboard. In the call to average() these 10 ints are then added and Divided by the number of ints to return the average, a float. Can someone see why I get for example: if the total is 227 then divided by 10 I get a return of 22.00000 instead of the correct answer 22.7.
0
8352
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
8275
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
8802
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
8697
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...
0
5612
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
4144
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...
0
4283
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1909
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1587
bsmnconsultancy
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...

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.