I wrote very simple code:
public static void Main (string[] args)
{
String str="1,0992748756871115E+41"; //yes, I know that is very large value
Double x=Convert.ToDouble(str);
Double res=Math.Cos(x);
Double resRound=Math.Round(res);
Console.WriteLine("x={0}\nres={1}\nresRound={2}", x, res, resRound);
}
And this code output very large value of res value: 1,09927487568711E+41 which a equals to Math.Cos's arguments:
I thought, that is a bug of Gtk# and decided to test what value returns this code compilled by .NET Framework and it returned same value!
Is that so the meaning of the function cos(x) exceeds the limits of segment from -1 to 1? How does it possible?
From the documentation:
Acceptable values of d range from approximately -9223372036854775295 to approximately 9223372036854775295. For values outside this range, the Cos method returns d unchanged rather than throwing an exception.
You can break down the expression to get the values like
Cost(A+B)= CosA *CosB -SinA * SinB
Break down as low as you can get within the documentation limit
Related
I have simple GUI a program where the real time plot(using WinForms chart) crashes due to non-double values like infinity or NaN.
So I want to filter values such as infinity,NaN or ect. And only plot valid double values. It can also be any other non-double type.
I try the following:
if(!double.IsInfinity(value)){
chart1.Series["mySerie"].Points.AddY(value);
}
But the above only checks if the value is not infinity not other non-double possibilities.
In my case Double. TryParse also would not work because it is used to check whether text is a double.
So in my case I receive data from a device normally a double. But sometimes it outputs non-double values and is there a quick fix for it?
To illustrate my comment with a range of acceptable values:
using System;
public class Program
{
public static bool Check(double x) {
double min = -1e6, max = 1e6;
return x > min && x < max;
}
public static void Main()
{
Console.WriteLine($"NaN {Check(double.NaN)}"); // False
Console.WriteLine($"-inf {Check(double.NegativeInfinity)}"); // False
Console.WriteLine($"-1e7 {Check(-1e7)}"); // False
Console.WriteLine($"0 {Check(0)}"); // True
Console.WriteLine($"1e7 {Check(1e7)}"); // False
Console.WriteLine($"+inf {Check(double.PositiveInfinity)}"); // False
}
}
This should work
if(Double.IsNaN(value)||Double.IsInfinity(value) ){
//do nothing
}else{
chart1.Series["mySerie"].Points.AddY(value);
}
Double has a few static methods that could help you do this. If you want to check the different states individually you can use the following methods:
Double.IsInfinite(value); //returns true if the value is infinite
Double.IsNaN(value); //returns true if the value is NaN
As you want to disregard other non-double values, I would suggest using one of the following:
Double.IsNormal(value); //returns true if the value is normal
Double.IsSubnormal(value); //returns true if the value is subnormal
Double.IsFinite(value) //returns true if the value is zero, normal, or subnormal
Any of these will help filter your input, so use the one that matches the input that you need. IsFinite is the only one of the 3 I believe that will return true if the value is 0
The entire set of methods for the Double type can be found here
I am writing unit tests that verify calculations in a database and there is a lot of rounding and truncating and stuff that mean that sometimes figures are slightly off.
When verifying, I'm finding a lot of times when things will pass but say they fail - for instance, the figure will be 1 and I'm getting 0.999999
I mean, I could just round everything into an integer but since I'm using a lot of randomized samples, eventually i'm going to get something like this
10.5
10.4999999999
one is going to round to 10, the other will round to 11.
How should I solve this problem where I need something to be approximately correct?
Define a tolerance value (aka an 'epsilon' or 'delta'), for instance, 0.00001, and then use to compare the difference like so:
if (Math.Abs(a - b) < delta)
{
// Values are within specified tolerance of each other....
}
You could use Double.Epsilon but you would have to use a multiplying factor.
Better still, write an extension method to do the same. We have something like Assert.AreSimiliar(a,b) in our unit tests.
Microsoft's Assert.AreEqual() method has an overload that takes a delta: public static void AreEqual(double expected, double actual, double delta)
NUnit also provides an overload to their Assert.AreEqual() method that allows for a delta to be provided.
You could provide a function that includes a parameter for an acceptable difference between two values. For example
// close is good for horseshoes, hand grenades, nuclear weapons, and doubles
static bool CloseEnoughForMe(double value1, double value2, double acceptableDifference)
{
return Math.Abs(value1 - value2) <= acceptableDifference;
}
And then call it
double value1 = 24.5;
double value2 = 24.4999;
bool equalValues = CloseEnoughForMe(value1, value2, 0.001);
If you wanted to be slightly professional about it, you could call the function ApproximatelyEquals or something along those lines.
static bool ApproximatelyEquals(this double value1, double value2, double acceptableDifference)
I haven't checked in which MS Test version were added but in v10.0.0.0 Assert.AreEqual methods have overloads what accept a delta parameter and do approximate comparison.
I.e.
https://msdn.microsoft.com/en-us/library/ms243458(v=vs.140).aspx
//
// Summary:
// Verifies that two specified doubles are equal, or within the specified accuracy
// of each other. The assertion fails if they are not within the specified accuracy
// of each other.
//
// Parameters:
// expected:
// The first double to compare. This is the double the unit test expects.
//
// actual:
// The second double to compare. This is the double the unit test produced.
//
// delta:
// The required accuracy. The assertion will fail only if expected is different
// from actual by more than delta.
//
// Exceptions:
// Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException:
// expected is different from actual by more than delta.
public static void AreEqual(double expected, double actual, double delta);
In NUnit, I like the clarity of this form:
double expected = 10.5;
double actual = 10.499999999;
double tolerance = 0.001;
Assert.That(actual, Is.EqualTo(expected).Within(tolerance));
One way to compare floating point numbers is to compare how many floating point representations that separate them. This solution is indifferent to the size of the numbers and thus you don't have to worry about the size of "epsilon" mentioned in other answers.
A description of the algorithm can be found here (the AlmostEqual2sComplement function in the end) and here is my C# version of it.
UPDATE:
The provided link is outdated. The new version which includes some improvements and bugfixes is here
public static class DoubleComparerExtensions
{
public static bool AlmostEquals(this double left, double right, long representationTolerance)
{
long leftAsBits = left.ToBits2Complement();
long rightAsBits = right.ToBits2Complement();
long floatingPointRepresentationsDiff = Math.Abs(leftAsBits - rightAsBits);
return (floatingPointRepresentationsDiff <= representationTolerance);
}
private static unsafe long ToBits2Complement(this double value)
{
double* valueAsDoublePtr = &value;
long* valueAsLongPtr = (long*)valueAsDoublePtr;
long valueAsLong = *valueAsLongPtr;
return valueAsLong < 0
? (long)(0x8000000000000000 - (ulong)valueAsLong)
: valueAsLong;
}
}
If you'd like to compare floats, change all double to float, all long to int and 0x8000000000000000 to 0x80000000.
With the representationTolerance parameter you can specify how big an error is tolerated. A higher value means a larger error is accepted. I normally use the value 10 as default.
The question was asking how to assert something was almost equal in unit testing. You assert something is almost equal by using the built-in Assert.AreEqual function. For example:
Assert.AreEqual(expected: 3.5, actual : 3.4999999, delta:0.1);
This test will pass. Problem solved and without having to write your own function!
FluentAssertions provides this functionality in a way that is perhaps clearer to the reader.
result.Should().BeApproximately(expectedResult, 0.01m);
I have a variable that is a decimal and i want to determine if it "is an int"
public bool IsanInt(decimal variable)
so if the variable passed in was 1, i want to return true
if it was 1.5, it would return false
.5 would be false
10 would be true
what is the best way to do this check?
Here you go:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(IsInt(3.0m)); // True
Console.WriteLine(IsInt(3.1m)); // False
}
public static bool IsInt(decimal variable)
{
return ((variable % 1) == 0);
}
}
Basically, that method is all you need. I just included the entire console program so that you can see the results.
EDIT:
So, after some brainstorming on the comments below, I found that it's incredibly difficult, if not impossible (I haven't found the way) to find if the value is decimal or "integer" if the decimal value being provided at its very high value. Decimal holds a higher value than even UInt64. When you run this line of code:
Console.WriteLine(Decimal.MaxValue - 0.5m);
Output:
79228162514264337593543950334
... you will see that it won't print the decimal value after the period. There is a maximum limitation that is forcing the truncation, so you'll never see that 0.5 being part of the that large value. My method can't fix that limitation. I'm not sure if there's anything that can do that within C# or .NET, but I'm all ears.
There's a good article on what you can and can't do with decimal... better than what MSDN provides in my opinion:
http://www.dotnetperls.com/decimal
public bool IsInteger(decimal value)
{
return value == Math.Round(value);
}
how about something like
return Math.Round(n) == n
So I am new to C# and I am having difficulty understanding out. As opposed to just returning something from a function
using System;
class ReturnTest
{
static double CalculateArea()
{
double r=5;
double area = r * r * Math.PI;
return area;
}
static void Main()
{
double output = CalculateArea();
Console.WriteLine("The area is {0:0.00}", output);
}
}
compare to this
using System;
class ReturnTest
{
static void CalculateArea(out double r)
{
r=5;
r= r * r * Math.PI;
}
static void Main()
{
double radius;
CalculateArea(out radius);
Console.WriteLine("The area is {0:0.00}",radius );
Console.ReadLine();
}
}
The first one is how I would generally do it. Is there a reason why I may want to use out instead of just a return statement? I understand that ref allows for 2 way communication, and that I generally shouldn't use ref unless the function is doing something with the variable I am sending it.
However is there a difference between out and return statements, like shown above? Syntax-wise is there a reason to favor one or the other?
A good use of out instead of return for the result is the Try pattern that you can see in certain APIs, for example Int32.TryParse(...). In this pattern, the return value is used to signal success or failure of the operation (as opposed to an exception), and the out parameter is used to return the actual result.
One of the advantages with respect to Int32.Parse is speed, since exceptions are avoided. Some benchmarks have been presented in this other question: Parsing Performance (If, TryParse, Try-Catch)
The out keyword is mostly used when you want to return more than one value from a method, without having to wrap the values in an object.
An example is the Int32.TryParse method, which has both a return value (a boolean representing the success of the attempt), and an out parameter that gets the value if the parsing was successful.
The method could return an object that contained both the boolean and the integer, but that would need for the object to be created on the heap, reducing the performance of the method.
Only time I tend to use out is when I need multiple things returned from a single method. Out lets you avoid wrapping multiple objects into a class for return. Check out the example at the Microsoft Out page.
You can have multiple out parameters, so if you need to return multiple values, it's a bit easier than creating a special class for your return values.
When one variable is concerned out and return are OK. But what if you wanted to return more than 1 values? Out helps in that.
static void CalculateArea(out double r, out double Foo)
{
//Can return 2 values in terms of out variables.
}
static double CalculateArea(double r)
{
// Will return only one value.
}
I am working with a Fortran program that expects floating point numbers to be input using Fortran's E format specifier, which is scientific notation, except the mantissa must be between 0 and 1. So instead of:
"3147.3" --> "3.1473E3",
it needs
"3147.3" --> "0.31473E4".
I am unable to modify the Fortran program, as it works with a few other programs that are also particular.
It would appear that the C# E format string would give me the former. Is there any simple way to achieve the latter in C#?
You could specify a custom format like so.
var num = 3147.3;
num.ToString("\\0.#####E0"); // "0.31473E4"
I think that you are solving a non-existent problem. It is true that the default of the Fortran E output specifier has a leading zero before the decimal point (this can be modified). But when the E specifier is used for input it is very tolerant and does not require the leading zero -- if you have a decimal point in the number and the number fits within the columns specified by the format, it will work.
Here is an example Fortran program, and an example input file.
program test_format
real :: num1, num2, num3
open (unit=16, file="numbers_3.txt", status='old', access='sequential', form='formatted', action='read' )
read (16, 1010 ) num1
read (16, 1010 ) num2
read (16, 1010 ) num3
1010 format (E9.5)
write (*, *) num1, num2, num3
stop
end program test_format
and the sample input with three different cases:
3.1473E3
0.31473E4
3147.3
I tested the program with gfortran and Intel ifort. The output was:
3147.300 3147.300 3147.300
So when performing input using Fortran's E format specifier, it is not necessary that the digit before the decimal point be zero. It is not even necessary that the input value use E-notation!
Edit / P.S. I translated the program to the fixed-form source layout of FORTRAN 77 and compiled it with g77 -- it read the three test numbers just fine. The E-format has been flexible for input for a long time -- probably since FORTRAN IV, perhaps longer.
The representaiton of floats or doubles are defined in IEEE754 / IEC 60559:1989. You should look to find libraries to extract mantissa and exponent. Then you could just divide by then to move to comma and subtract the number of steps from the exponent to form your solution.
You could take something similar to Jeff M's solution, and implement it via extension method:
public static class DoubleExtensions
{
public static string ToFortranDouble(this double value)
{
return value.ToString("\\0.#####E0");
}
}
class Program
{
static void Main(string[] args)
{
string fortranValue = 3147.3.ToFortranDouble();
System.Console.WriteLine(fortranValue);
}
}
Or for something a little more complicated (not sure how much precision Fortran floats/doubles give):
public static class DoubleExtensions
{
public static string ToFortranDouble(this double value)
{
return value.ToFortranDouble(4);
}
public static string ToFortranDouble(this double value, int precision)
{
return string.Format(value.ToString(
string.Format("\\0.{0}E0", new string('#', precision))
));
}
}