Math.Round with Mid point Rounding [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
This sample code is producing unexpected result
decimal s = 463.815M;
decimal a = Math.Round(s, 2, MidpointRounding.AwayFromZero);
decimal b = Math.Round(s, 2, MidpointRounding.ToEven);
decimal t = 4.685M;
decimal c = Math.Round(t, 2, MidpointRounding.AwayFromZero);
decimal d = Math.Round(t, 2, MidpointRounding.ToEven);
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
Console.Read();
It produces
463.82
463.82
4.69
4.68
I was expecting a and c to have incremented by 1 which c did but to my surprise a didn't. Can anyone explain the reason for this please?
[update]
a and c are expected to have same results as:
a has .815 and c also has .685 i.e. 5 at the end.
a and c both are using MidpointRounding.AwayFromZero

This is the expected result, because 0.815 fraction is rounded up to 0.82. The same exact thing happens when you round to even, because 2 is even.
The result would be different if you used 0.825 as a fraction:
decimal s = 463.825M;
decimal a = Math.Round(s, 2, MidpointRounding.AwayFromZero);
decimal b = Math.Round(s, 2, MidpointRounding.ToEven);
Now the code prints
463.83
463.82
to illustrate the difference between MidpointRounding.AwayFromZero and MidpointRounding.ToEven.

Related

c# gives wrong answer to cos [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 days ago.
Improve this question
the program wants the angle between two vectors.
I want to get the inverse cosine of a number but it gives the wrong answer in degrees and radians, even after adding the rad to deg equation
dis = 1 / Math.Cos(1); //output: 1.85
it's supposed to be 0 in radians and degrees
dis = 1 / Math.Cos(0.5); //output 1.14
dis = (dis * Math.PI) / 180; //output 0.02
the correct answer:
in radians: 1.04719755
in degrees: 60
You are looking for Math.Acos which returns the angle whose cosine is given value:
double[] tests = new double[] {
0,
0.5,
1.0
};
string result = string.Join(Environment.NewLine, tests
.Select(test => $"{test,5:f2} : {Math.Acos(test),5:f2} : {Math.Acos(test) * 180 / Math.PI,5:f2} deg"));
Console.Write(result);
Output:
0.00 : 1.57 : 90.00 deg
0.50 : 1.05 : 60.00 deg
1.00 : 0.00 : 0.00 deg

Difference between integral and float point arithmetic in C#? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
What is difference between integral and float point arithmetic in C#?
I tried looking online and reading articles but it was not answering the question directly.
Several arithmetic operators are affected by integer vs floating point logic. The most common one that trips people up is the divisor operator
Integer division
For the operands of integer types, the result of the / operator is of an integer type and equals the quotient of the two operands rounded towards zero:
Floating-point division
For the float, double, and decimal types, the result of the / operator is the quotient of the two operands:
an example is shown below.
var intResult = 5/2; //result is 2, not 2.5
var doubleResult = 5/2.0; //result is 2.5
Other items affected by integer vs floating point logic are the following
remainder operator
Integer remainder
For the operands of integer types, the result of a % b is the value produced by a - (a / b) * b. The sign of the non-zero remainder is the same as that of the first operand...
Floating-point remainder
For the float and double operands, the result of x % y for the finite x and y is the value z such that
The sign of z, if non-zero, is the same as the sign of x.
The absolute value of z is the value produced by |x| - n * |y| where n is the largest possible integer that is less than or equal to |x| / |y| and |x| and |y| are the absolute values of x and y, respectively.
The remainder operator just produces a remainder for both integer and floating point operations. The description for a floating point remainder just has to be more descriptive since it is operating on floating point values. Examples are shown below
Console.WriteLine(5 % 4); // output: 1
Console.WriteLine(5 % -4); // output: 1
Console.WriteLine(-5 % 4); // output: -1
Console.WriteLine(-5 % -4); // output: -1
Console.WriteLine(-5.2f % 2.0f); // output: -1.2
Console.WriteLine(5.9 % 3.1); // output: 2.8
Console.WriteLine(5.9m % 3.1m); // output: 2.8
Another example just to show that integer remainders and float remainders are the same. Only difference is one returns an int and the other returns a double.
Console.WriteLine(5.0 % 4.0); // output: 1.0
arithmetic overflow and divide by zero
Integer arithmetic overflow
Integer division by zero always throws a DivideByZeroException.
In case of integer arithmetic overflow, an overflow checking context, which can be checked or unchecked, controls the resulting behavior:
In a checked context, if overflow happens in a constant expression, a compile-time error occurs. Otherwise, when the operation is performed at run time, an OverflowException is thrown.
In an unchecked context, the result is truncated by discarding any high-order bits that don't fit in the destination type.
Along with the checked and unchecked statements, you can use the checked and unchecked operators to control the overflow checking context, in which an expression is evaluated:
int a = int.MaxValue;
int b = 3;
Console.WriteLine(unchecked(a + b)); // output: -2147483646
try
{
int d = checked(a + b);
}
catch(OverflowException)
{
Console.WriteLine($"Overflow occured when adding {a} to {b}.");
}
Floating-point arithmetic overflow
Arithmetic operations with the float and double types never throw an exception. The result of arithmetic operations with those types can be one of special values that represent infinity and not-a-number:
double a = 1.0 / 0.0;
Console.WriteLine(a); // output: Infinity
Console.WriteLine(double.IsInfinity(a)); // output: True
Console.WriteLine(double.MaxValue + double.MaxValue); // output: Infinity
double b = 0.0 / 0.0;
Console.WriteLine(b); // output: NaN
Console.WriteLine(double.IsNaN(b)); // output: True
Basically, ints will throw overflow exceptions depending on if you are checking for overflow or not and will always throw divide by zero exceptions. Floating point values will not overflow, but instead take on a special value of infinity, or in some cases not a number (NaN)
These differences exist for almost every programming language, but the specifics may be handled differently.

c# - outputting a value of infinity [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have part of the calculation that is modified to explain what issue I'm having. I'm converting a working Java code into a c# application.
A double variable is declared doing the following calculation and the following input values being passed along for example:
double input1 = 45
double input2 = 42
double input3 = 1
double a = (input1 - input2 * Math.Pow(input3, 2.0)) / (1 - Math.Pow(input3, 2.0));
This outputs as an Infinite in c# but Java shows the value. With infinite being outputted, the other calculations below are affected.
double b = input1 + input2 - 2 * a (becomes -Infinite)
double c = b + a (gives you NaN)
a,b, and c are outputted into individual text boxes and each either show as Infinite or NaN.
Textbox1.Text = a.ToString("F") (Infinite)
Textbox2.Text = b.ToString("F") (-Infinite)
Textbox3.Text = c.ToString("F") (NaN)
I know that this is due to IEEE standards, but is there actually a way that variable a shows the value instead of showing infinite so that it doesn't affect the calculations or output the results into a text box in 2 decimal places?
Your code is returning a value 0 for the divide part which results into infinity value. which is true here there is nothing wrong in the code. You need to check the calculation.
double input1 = 45;
double input2 = 42;
double input3 = 1;
double a = (input1 - input2 * Math.Pow(input3, 2.0))
/ (1 - Math.Pow(input3, 2.0));
Console.WriteLine((input1 - input2 * Math.Pow(input3, 2.0)));
Console.WriteLine((1 - Math.Pow(input3, 2.0)));
Console.WriteLine(a);
check the output on console.
I pasted into a Java test program the code you posted for calculating a, and made minimal changes to turn it into compilable Java. I added ; to the first three declarations, and changed Math.Pow to Math.pow:
public class Test {
public static void main(String[] args) {
double input1 = 45;
double input2 = 42;
double input3 = 1;
double a = (input1 - input2 * Math.pow(input3, 2.0))
/ (1 - Math.pow(input3, 2.0));
System.out.println(a);
}
}
The program prints, as expected, "Infinity".
If your Java program is getting something different, there is some error in how you are converting it to C#.

Need help to convert formula into C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I got this formula,
R/Rs = (5800/9500)2(2.5123.37)1/2 = 1.76
How do I turn that into C# so that the value is 1.76. Don't understand what you do with the 2 and 1/2?
Formula is from http://skyserver.sdss.org/dr5/en/proj/advanced/hr/radius1.asp
You are looking for Math.Pow
Math.Pow(5800d/9500d, 2)*Math.Pow(Math.Pow(2.512, 3.37),0.5);
And using 5800d/9500d is important here (forcing double, one of the d's should do), as it would otherwise do integer division, leaving you with 0^2 and overall a big 0...
If you put this into a method taking the necessary double values that should be irrelevant.
You can do :
double res = Math.Pow(5800 / 9500d, 2) * Math.Sqrt(Math.Pow(2.512, 3.37));
Console.WriteLine(res.ToString("0.00"));
output :
1.76
Working demo
A power of 0.5 is a square root.
Its
double i = 5800.0 / 9500;
i = Math.Pow(i, 2);
double x = Math.Pow(2.512, 3.37);
x = Math.Sqrt(x);
x = x * i;
x = Math.Round(x, 2);
OR
Math.Round(Math.Pow(5800.0 / 9500, 2) * Math.Sqrt(Math.Pow(2.512, 3.37)), 2)
The trick is here is in the first line itself. If you will divide 5800 by 9500, it will return zero as division will happen in integers. So to do an actual division resulting in fractions one the the values have to be converted into decimal which i did by converting 5800 to 5800.0

C# Method Calculate [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I am trying to calculate the perimeter of a circle using method
for some reason I get an error at:
//double p = 2 * Math.PI * r;
I am new to using method please help and show me what I did wrong.
static void Main(string[] args)
{
double perimeter;
Console.Write("Enter Perimeter: ");
double.TryParse(Console.ReadLine(), out perimeter);
double per = PerimeterOfCircle(perimeter);
Console.WriteLine("\nPerimeter of Circle = {0}",
per.ToString("F3"));
Console.ReadKey();
}
static double PerimeterOfCircle(double p)
{
double p = 2 * Math.PI * r;
return p;
}
Looks like you have the parameter named incorrectly. Change it to r:
static double PerimeterOfCircle(double r) // <-- changed from p to r here
{
double p = 2 * Math.PI * r;
return p;
}
Also you can embed the format string within WriteLine:
Console.WriteLine("\nPerimeter of Circle = {0:F3}", per);
Simple: You did not provide a value for r. The code does not even compile.

Categories