Can't convert "float" to "mathf" (C#) - c#

I just discovered MathF (wonderful tool). Like any new tool, we're going through some... growing pains. I'm working on unit conversion script. Here's my code. I thought MathF.Pow requires two floats, in this case 10 and 6. But apparently that's frowned upon. Any ideas?
Mathf megagram;
void Start () {
megagram = Mathf.Pow(10,6);

Mathf.Pow returns a float while you are assigning the return value (float) to megagram (MathF type)

float megagram;
void Start ()
{
megagram = Mathf.Pow(10f,6f);
}
If you write 6 or 10, compiler thinks that you use Int32. For floats write f suffix - 6f, 10f
Also Mathf.Pow returns float, not a Mathf type

Related

Is there a c# function to test if two doubles are 'approximately equal'? [duplicate]

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);

Missing a cast when using Math.Ceiling [duplicate]

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.

.NET Core float variable don't print decimals

I assign 2097151.3 to the float variable and the application prints only the integer part. Possible bug?
public static void Main(string[] args)
{
float foo = 2097151.3F;
Console.WriteLine(foo); // prints 2097151
Console.ReadKey();
}
I'm running a .NET Core console application.
Nope. Floating point numbers have been around since the 1940s. A float is only really good for 7 significant figures.
The nearest float to 2097151.3 is 2097151.25, and WriteLine is clever enough to know that and so it truncates accordingly.
If you want precise decimal values then use a decimal type.

MiscUtils Operator - multiply by scalar

I am implementing the next function:
private bool CheckRelativeIncrease(T pVal1, T pVal2, out T pFluctuation, int x)
where I compare if pVal2 has increased more than a "x%" over pVal1. I am using Generics to make the function work with int, short... I am using MiscUtils.Operator but the problem is that I can't mix known and unknown types. The following code doesn't work:
bool increased = false;
int comparer = Comparer.Default.Compare(pVal1, pVal2);
pFluctuation = Operator<T>.Zero;
if (comparer > 0) {
int factor = (int)(1 + (x / 100));
pFluctuation = Operator.Multiply(factor, pVal2);
comparer = Comparer.Default.Compare(pVal1, pFluctuation);
if (comparer >= 0)
increased = true;
}
return increased;
"Operator.Multiply" gives me an error because 'factor' has not the same type as 'pVal2'.
Any ideas?
Thanks in advance,
Silvia
I don't believe we currently support operators on mixed types - but if you look at the code in Operator<T> it should be pretty easy to adapt it. Feel free to send me a patch :)
Basically you'll need an Operator<T1, T2, TResult> which looks like Operator<TValue, TResult> except it uses different types for the different inputs and outputs. You'll need to specify what the expected result type is, of course - if you're multiply T by int, would you expect the result to be int, T or something else?
If you're using C# 4 and .NET 4, you may want to consider using dynamic typing instead...
There is also two-type multiply operation which you can use, according to this documentation:
public static TArg1 MultiplyAlternative(TArg1 value1, TArg2 value2)
Write another function to cast one type as another type. Make a nested call to that function within your code and problem solved.

What is the best way to calculate a formula when using an int as a divisor

Often I find myself having a expression where a division by int is a part of a large formula. I will give you a simple example that illustrate this problem:
int a = 2;
int b = 4;
int c = 5;
int d = a * (b / c);
In this case, d equals 0 as expected, but I would like this to be 1 since 4/5 multiplied by 2 is 1 3/5 and when converted to int get's "rounded" to 1. So I find myself having to cast c to double, and then since that makes the expression a double also, casting the entire expression to int. This code looks like this:
int a = 2;
int b = 4;
int c = 5;
int d = (int)(a * (b / (double)c));
In this small example it's not that bad, but in a big formula this get's quite messy.
Also, I guess that casting will take a (small) hit on performance.
So my question is basically if there is any better approach to this than casting both divisor and result.
I know that in this example, changing a*(b/c) to (a*b)/c would solve the problem, but in larger real-life scenarios, making this change will not be possible.
EDIT (added a case from an existing program):
In this case I'm caclulating the position of a scrollbar according to the size of the scrollbar, and the size of it's container. So if there is double the elements to fit on the page, the scrollbar will be half the height of the container, and if we have scrolled through half of the elements possible, that means that the scroller position should be moved 1/4 down so it will reside in the middle of the container. The calculations work as they should, and it displays fine. I just don't like how the expression looks in my code.
The important parts of the code is put and appended here:
int scrollerheight = (menusize.Height * menusize.Height) / originalheight;
int maxofset = originalheight - menusize.Height;
int scrollerposition = (int)((menusize.Height - scrollerheight) * (_overlayofset / (double)maxofset));
originalheight here is the height of all elements, so in the case described above, this will be the double of menusize.Height.
Disclaimer: I typed all this out, and then I thought, Should I even post this? I mean, it's a pretty bad idea and therefore doesn't really help the OP... In the end I figured, hey, I already typed it all out; I might as well go ahead and click "Post Your Answer." Even though it's a "bad" idea, it's kind of interesting (to me, anyway). So maybe you'll benefit in some strange way by reading it.
For some reason I have a suspicion the above disclaimer's not going to protect me from downvotes, though...
Here's a totally crazy idea.
I would actually not recommend putting this into any sort of production environment, at all, because I literally thought of it just now, which means I haven't really thought it through completely, and I'm sure there are about a billion problems with it. It's just an idea.
But the basic concept is to create a type that can be used for arithmetic expressions, internally using a double for every term in the expression, only to be evaluated as the desired type (in this case: int) at the end.
You'd start with a type like this:
// Probably you'd make this implement IEquatable<Term>, IEquatable<double>, etc.
// Probably you'd also give it a more descriptive, less ambiguous name.
// Probably you also just flat-out wouldn't use it at all.
struct Term
{
readonly double _value;
internal Term(double value)
{
_value = value;
}
public override bool Equals(object obj)
{
// You would want to override this, of course...
}
public override int GetHashCode()
{
// ...as well as this...
return _value.GetHashCode();
}
public override string ToString()
{
// ...as well as this.
return _value.ToString();
}
}
Then you'd define implicit conversions to/from double and the type(s) you want to support (again: int). Like this:
public static implicit operator Term(int x)
{
return new Term((double)x);
}
public static implicit operator int(Term x)
{
return (int)x._value;
}
// ...and so on.
Next, define the operations themselves: Plus, Minus, etc. In the case of your example code, we'd need Times (for *) and DividedBy (for /):
public Term Times(Term multiplier)
{
// This would work because you would've defined an implicit conversion
// from double to Term.
return _value * multiplier._value;
}
public Term DividedBy(Term divisor)
{
// Same as above.
return _value / divisor._value;
}
Lastly, write a static helper class to enable you to perform Term-based operations on whatever types you want to work with (probably just int for starters):
public static class TermHelper
{
public static Term Times(this int number, Term multiplier)
{
return ((Term)number).Times(multiplier);
}
public static Term DividedBy(this int number, Term divisor)
{
return ((Term)number).DividedBy(divisor);
}
}
What would all of this buy you? Practically nothing! But it would clean up your expressions, hiding away all those unsightly explicit casts, making your code significantly more attractive and considerably more impossible to debug. (Once again, this is not an endorsement, just a crazy-ass idea.)
So instead of this:
int d = (int)(a * (b / (double)c)); // Output: 2
You'd have this:
int d = a.Times(b.DividedBy(c)); // Output: 2
Is it worth it?
Well, if having to write casting operations were the worst thing in the world, like, even worse than relying on code that's too clever for its own good, then maybe a solution like this would be worth pursuing.
Since the above is clearly not true... the answer is a pretty emphatic NO. But I just thought I'd share this idea anyway, to show that such a thing is (maybe) possible.
First of all, C# truncates the result of int division, and when casting to int. There's no rounding.
There's no way to do b / c first without any conversions.
Multiply b times 100. Then divide by 100 at the end.
In this case, I would suggest Using double instead, because you don't need 'exact' precision.
However, if you really feel you want to do it all without floating-point operation, I would suggest creating some kind of fraction class, which is far more complex and less efficient but you can keep track of all dividend and divisor and then calculate it all at once.

Categories