-
Notifications
You must be signed in to change notification settings - Fork 0
Code in Depth
Sandesh Kota edited this page Mar 4, 2019
·
20 revisions
- Operations
Single one = 1;
Single three = 3;
Single x = one / three;
Double result = 3 * x ;
result == ?
Answers?
== 1.0, < 1.0, > 1.0
Math.Round(result, 7) == 1
What if? Single result = 3 * x ;
Reason: Base2 airthmatic
- Example 2
Double x = .1;
Double result = 10 * x ;
Double result2 = x + x + x + x + x + x + x + x + x + x;
result == result2 ?
Console.WriteLine( "{0} - {1}" , result, result2)
Console.WriteLine( "{0:R} - {1:R}" , result, result2)
Reason: Can't be held exactly in Base 2 system so there is a rounding error
- Division
Int maxDiscountPercent = 30;
Int markupPercent = 20;
Int niceFactor = 30;
Double discount = maxDiscountPercent * ( markupPercent / niceFactor) ;
discount ?
== 0
Reason: Integer division in C# truncates the value to nearest integer. So 20 / 30 becomes Zero
Error Code:
Int x = 9, int y = 10; int z = 100;
decimal interim = x / y;
Decimal result = z / interim ;
- Divide By Zero
Int zero = 0;
Int three = 3;
Int result = 3 / 0;
-- Int, Decimal => Throws exception
-- Single / Double => They can hold Infinity (Double.PositiveInfinity , Double.NegativeInfinity)
- Rounding
Math.Round(3.5); ==> 4
Math.Round(4.5); ==> 4
Reason: .Net rounds mid-point number to the nearest Even digit -> Banker's rounding
Math.Round(4.5, MidpointRounding.AwayFromZero); ==> 5
- Top Of Type
Int top = int.MaxValue;
Int next = top + 1;
-- Int => Airthmatic overflow is not turned ON by default => Value rolls over to minimum value
-- Decimal => overflow exception
-- Single, Double => Infinity is supported => top + 1 is same as top.
- Single [Base2-32bit] , Double [Base2-64bit] & Decimal [Base10-128bit]
- Use "fuzzy" comparisons for Single & Double Data Types
- Base 10 & Base 2 rounds differently
- Avoid data Conversions between fractional type
- Decimal performance is 10 times slower than Single & Double
- Decimal for money, Double for everything else