Answered by:
Precision in C# without Parenthesis
Question

Hello,
We have Precision in result when we don't use parenthesis.We don't have precision in result when we use parentheses.
In two cases we have divided an integer by double (1/fraction) but we have different result.static void Main(string[] args) { Console.WriteLine("Number??"); int number = Int32.Parse(Console.ReadLine()); double sum = 0; for (int i = 1; i <= number; i++) { sum += 1.0 / (Math.Sqrt(i) + Math.Sqrt(i + 1)); // and sum += 1.0 / Math.Sqrt(i) + Math.Sqrt(i + 1); } Console.WriteLine(sum); }
 Edited by Arash_89 Saturday, October 26, 2019 12:07 PM
Answers
All replies

In two cases we have divided an integer by double (1/fraction) but we have different result.
Operator precedence causes different results.
Division occurs before addition. When you use parentheses
you force the addition to occur before the division.
 Wayne

In two cases we have divided an integer by double (1/fraction) but we have different result.
1.0 is not an integer, it is a double.
Operator precedence causes different results.
Division occurs before addition. When you use parentheses
you force the addition to occur before the division.
 Wayne
Thank you,
But in both case double divide by double and result should be double.
 Edited by Arash_89 Saturday, October 26, 2019 12:37 PM



So why in first case we don't need use composite formatting like "{0:N2}" ? and in second case we need.
What is the difference?
zero so WriteLine shows it.
In the second case it IS zero so if you don't specify that you want a certain
number of digits after the decimal point to *always* be printed none are.
If you do this:
Console.WriteLine(sum + 0.5);
then it will print
1.5
 Wayne
 Proposed as answer by EckiS Sunday, October 27, 2019 9:11 AM

I wrote some software for designing printed circuit boards.
One module looks after designing component footprints.
The system is based on imperial measurement but also has to allow metric measurements.
I made a loop for putting down component pcb pads in a row.
I found in metric mode any errors accumulated as I got further along the row.
So to get around this I keep the original distance between pads in a double and multiply by that to get the new pad positions. This gave much smaller error.
n.Wright

Yes. In a system that involves the physical world, you have to be extremely careful about roundoff errors. In a case like yours, I don't think I would use floating point arithmetic at all. Store everything in integers in some base unit, like micrometers or mils. You can do a floating point calculation to convert that between imperial and metric at the last minute, but don't store them that way.
Tim Roberts  Driver MVP Emeritus  Providenza & Boekelheide, Inc.