This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed 5 years ago.
I have the following using MathNet library where child1 is -4.09 and child2 is -4.162. The result after Expression.Real((double1 - double2)) returns 0.072000000000000064. It should be 0.072. Can anyone please help me understand what is going on?
private static Expression GetSimplifiedExpression(Expression child1, Expression child2, LaTeXTokenType tokenType)
{
double double1 = Evaluate.Evaluate(null, child1).RealValue;
double double2 = Evaluate.Evaluate(null, child2).RealValue;
return Expression.Real((double1 - double2));
}
First, let's convert decimal to binary:
-4.09 = -100.00010111000010100011110101110000101000111101011100001010001111...
-4.162 = -100.00101001011110001101010011111101111100111011011001000101101000...
Then, subtract those two binaries. The result in binary is:
0.00010010011011101001011110001101010011111101111100111011011001...
which is approximately equal to decimal 0.07199999999999999998.
It is not exactly 0.072000000000000064, but I think you could get the idea behind it. If you want the exact result, you could cast double to decimal:
var decimal1 = (decimal) double1;
var decimal2 = (decimal) double2;
Related
This question already has answers here:
C# casting double to float error [duplicate]
(2 answers)
Closed 3 years ago.
I've just started working with C# and Visual Studio for college, and I'm struggling with using the Math.Ceiling in order to have a float value round up to the next integer before it's outputted.
Visual Studio says I'm missing a cast, but I don't really know where. It's probably really simple, but being new I don't really know where to start.
The final line shown is where I've got a problem.
I could just do with someone telling me where I'm going wrong here.
I tried using a float.Parse around the Math.Ceiling but that doesn't work apparently
const float FencePanelWidth = 1.5f;
float GWidth;
float GLength;
float GPerimetre;
float FencePanelsNeed;
float FencePanelsNeed2;
Console.Write("");
Console.Write("");
GWidth = float.Parse(Console.ReadLine());
Console.Write("");
GLength = float.Parse(Console.ReadLine());
GPerimetre = (GLength * 2) + GWidth;
FencePanelsNeed = GPerimetre / FencePanelWidth;
FencePanelsNeed2 = Math.Ceiling(FencePanelsNeed);
If FencePanelsNeed was say 7.24, I'd want FencePanelsNeed2 to be 8.
The Math.Ceiling method has only two overloads:
public static decimal Ceiling (decimal d); - Docs.
public static double Ceiling (double a); - Docs.
In your case, it uses the second overload (because the passed float value gets casted to double, and therefore, returns a double.
What you should do is cast the returned value to int or float:
FencePanelsNeed2 = (int)Math.Ceiling(FencePanelsNeed); // Or:
//FencePanelsNeed2 = (float)Math.Ceiling(FencePanelsNeed);
If you cast it to an int, you might also declare your FencePanelsNeed2 as int instead of float.
Note that if FencePanelsNeed2 were declared as double, you wouldn't get that error in the first place because no cast would be needed. So, it only comes down to which type you want to use.
Just cast it to an int and add 1, will always work
using System;
public class Program
{
const float FencePanelWidth = 7.24f;
public static void Main()
{
var FencePanelsNeed2 = (int)FencePanelWidth < FencePanelWidth ? (int)FencePanelWidth + 1 : (int)FencePanelWidth;
Console.WriteLine(FencePanelsNeed2);
}
}
Try it for yourself.
This question already has answers here:
C# converting string to int goes wrong
(5 answers)
Closed 3 years ago.
The type conversion doesn't function as expected
I broke down the problem but it still occurs
string a = "123";
int i = Convert.ToInt32(a[0]);
Console.WriteLine(i);
I expect the result of 1 but I get 49. I can't imagine how.
When you do the indexer a[0] you get a char which for 1 is char code number 49. Do Convert.ToInt32(a[0].ToString()) or subtract 48 from the result you get instead to get the numerical representation.
This question already has answers here:
Convert a text fraction to a decimal
(5 answers)
Parse Math Expression [duplicate]
(9 answers)
Closed 3 years ago.
I have created a method that splits a string a^b and converts a and b to doubles. However, if I input the value of either a or b using a fraction (for example 3/5 instead of 0.6) the method doesn't work; it only allows me to input it like 0.6. Why is this, and is it possible to fix it?
The code is shown below:
public static double Coefficient()
{
while (true)
{
string input = Console.ReadLine();
string[] items = input.Split('^');
if (items.Length == 1)
{
if (double.TryParse(items[0], out double A))
return A;
}
else if (items.Length == 2)
{
if (double.TryParse(items[0], out double A) &
double.TryParse(items[1], out double B))
return Math.Pow(A, B);
}
Console.WriteLine("\nPlease follow the specified input form.");
}
}
You're trying to parse expressions with methods that only know how to handle specifically formatted numbers as inputs. You need to either write an equation parser or split your inputs appropriately. You are already doing this by splitting ^ - you can do the same with /.
In fact, there are libraries that already do this.
This question already has answers here:
How to convert list of strings to doubles?
(5 answers)
Closed 3 years ago.
Is there an easy way to directly convert my list of string into double data type and get the average value.
Here is my current list result:
["6.3000e-009", "7.3319e-009", "7.8303e-009"]
expected result:
7.15E-09
Any suggestion/Comments TIA.
You can use Linq to get the average:
var avg = input.Select(double.Parse).Average();
you can use Linq to objects to do this quite easily
something like..(untested)
var result = yourArray.Select( s => Double.Parse(s) ).Average();
This question already has answers here:
Int32.TryParse() returns zero on failure - success or failure?
(6 answers)
Closed 5 years ago.
I'm baffled on the tiny piece of code below that fails to return 957 as I would expect. I'm kind of embarrassed to post but I can't see the problem.
using System;
namespace ConsoleApp1
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(ConvertToInteger("957.13"));
}
private static string ConvertToInteger(string timeStartIn)
{
Int32.TryParse(timeStartIn, out var timeStart);
return timeStart.ToString();
}
}
}
You should check Int32.TryParse method help.
It says:
When this method returns, contains the 32-bit signed integer value equivalent of the number contained in s, if the conversion succeeded, or zero if the conversion failed.
Since 957.13 is a string representing a decimal value, TryParse method returns 0 because a decimal number is not an integer one.
You are dealing with a float or a decimal type, use a floor or ceiling function then you can convert it to a full number integer. You could also convert it to a string and split it by the decimal point, then use only the first segment and convert that to a full number integer.
NOTE: The string method does not take rounding into account.