Round algorithm for integer and decimal numbers with C# [duplicate] - c#

For example, does an operator exist to handle this?
float Result, Number1, Number2;
Number1 = 2;
Number2 = 2;
Result = Number1 (operator) Number2;
In the past the ^ operator has served as an exponential operator in other languages, but in C# it is a bit-wise operator.
Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?

The C# language doesn't have a power operator. However, the .NET Framework offers the Math.Pow method:
Returns a specified number raised to the specified power.
So your example would look like this:
float Result, Number1, Number2;
Number1 = 2;
Number2 = 2;
Result = Math.Pow(Number1, Number2);

I stumbled on this post looking to use scientific notation in my code, I used
4.95*Math.Pow(10,-10);
But afterwards I found out you can do
4.95E-10;
Just thought I would add this for anyone in a similar situation that I was in.

There is a blog post on MSDN about why an exponent operator does NOT exists from the C# team.
It would be possible to add a power
operator to the language, but
performing this operation is a fairly
rare thing to do in most programs, and
it doesn't seem justified to add an
operator when calling Math.Pow() is
simple.
You asked:
Do I have to write a loop or include
another namespace to handle
exponential operations? If so, how do
I handle exponential operations using
non-integers?
Math.Pow supports double parameters so there is no need for you to write your own.

The lack of an exponential operator for C# was a big annoyance for us when looking for a new language to convert our calculation software to from the good ol' vb6.
I'm glad we went with C# but it still annoys me whenever I'm writing a complex equation including exponents. The Math.Pow() method makes equations quite hard to read IMO.
Our solution was to create a special DoubleX class where we override the ^-operator (see below)
This works fairly well as long as you declare at least one of the variables as DoubleX:
DoubleX a = 2;
DoubleX b = 3;
Console.WriteLine($"a = {a}, b = {b}, a^b = {a ^ b}");
or use an explicit converter on standard doubles:
double c = 2;
double d = 3;
Console.WriteLine($"c = {c}, d = {d}, c^d = {c ^ (DoubleX)d}"); // Need explicit converter
One problem with this method though is that the exponent is calculated in the wrong order compared to other operators. This can be avoided by always putting an extra ( ) around the operation which again makes it a bit harder to read the equations:
DoubleX a = 2;
DoubleX b = 3;
Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + a ^ b}"); // Wrong result
Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + (a ^ b)}"); // Correct result
I hope this can be of help to others who uses a lot of complex equations in their code, and maybe someone even has an idea of how to improve this method?!
DoubleX class:
using System;
namespace ExponentialOperator
{
/// <summary>
/// Double class that uses ^ as exponential operator
/// </summary>
public class DoubleX
{
#region ---------------- Fields ----------------
private readonly double _value;
#endregion ------------- Fields ----------------
#region -------------- Properties --------------
public double Value
{
get { return _value; }
}
#endregion ----------- Properties --------------
#region ------------- Constructors -------------
public DoubleX(double value)
{
_value = value;
}
public DoubleX(int value)
{
_value = Convert.ToDouble(value);
}
#endregion ---------- Constructors -------------
#region --------------- Methods ----------------
public override string ToString()
{
return _value.ToString();
}
#endregion ------------ Methods ----------------
#region -------------- Operators ---------------
// Change the ^ operator to be used for exponents.
public static DoubleX operator ^(DoubleX value, DoubleX exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(DoubleX value, double exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(double value, DoubleX exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(DoubleX value, int exponent)
{
return Math.Pow(value, exponent);
}
#endregion ----------- Operators ---------------
#region -------------- Converters --------------
// Allow implicit convertion
public static implicit operator DoubleX(double value)
{
return new DoubleX(value);
}
public static implicit operator DoubleX(int value)
{
return new DoubleX(value);
}
public static implicit operator Double(DoubleX value)
{
return value._value;
}
#endregion ----------- Converters --------------
}
}

Since no-one has yet wrote a function to do this with two integers, here's one way:
private static long CalculatePower(int number, int powerOf)
{
long result = number;
for (int i = 2; i <= powerOf; i++)
result *= number;
return result;
}
Alternatively in VB.NET:
Private Function CalculatePower(ByVal number As Integer, ByVal powerOf As Integer) As Long
Dim result As Long = number
For i As Integer = 2 To powerOf
result = result * number
Next
Return result
End Function
CalculatePower(5, 3) ' 125
CalculatePower(8, 4) ' 4096
CalculatePower(6, 2) ' 36

For what it's worth I do miss the ^ operator when raising a power of 2 to define a binary constant. Can't use Math.Pow() there, but shifting an unsigned int of 1 to the left by the exponent's value works. When I needed to define a constant of (2^24)-1:
public static int Phase_count = 24;
public static uint PatternDecimal_Max = ((uint)1 << Phase_count) - 1;
Remember the types must be (uint) << (int).

I'm surprised no one has mentioned this, but for the simple (and probably most encountered) case of squaring, you just multiply by itself.
float someNumber;
float result = someNumber * someNumber;

A good power function would be
public long Power(int number, int power) {
if (number == 0) return 0;
long t = number;
int e = power;
int result = 1;
for(i=0; i<sizeof(int); i++) {
if (e & 1 == 1) result *= t;
e >>= 1;
if (e==0) break;
t = t * t;
}
}
The Math.Pow function uses the processor power function and is more efficient.

It's no operator but you can write your own extension function.
public static double Pow(this double value, double exponent)
{
return Math.Pow(value, exponent);
}
This allows you to write
a.Pow(b);
instead of
Math.Pow(a, b);
I think that makes the relation between a and b a bit clearer + you avoid writing 'Math' over and over again.

Related

When the int variable is more than 10 digits

When the int variable is more than 10 digits, an error occurs and the number becomes negative.
Why is this happening and how can I solve the problem?
This is my code:
UnityWebRequest www = new UnityWebRequest("https://api.hypixel.net/skyblock/bazaar");
www.downloadHandler = new DownloadHandlerBuffer();
yield return www.SendWebRequest();
JSONNode itemsData = JSON.Parse(www.downloadHandler.text);
unixtimeOnline = itemsData2["lastUpdated"];
Debug.Log(unixtimeOnline);
// output -2147483648
tl;dr
Simply use ulong instead of int for unixtimeOnline
ulong unixtimeOnline = itemsData2["lastUpdated"];
What happened?
As was already mentioned int (or also System.Int32) has 32 bits.
The int.MaxValue is
2147483647
no int can be higher than that. What you get is basically a byte overflow.
From the JSON.Parse I suspect you are using SimpleJson
and if you have
int unixtimeOnline = itemsData2["lastUpdated"];
it will implicitly use
public static implicit operator int(JSONNode d)
{
return (d == null) ? 0 : d.AsInt;
}
which uses AsInt
public virtual int AsInt
{
get { return (int)AsDouble; }
set { AsDouble = value; }
}
which is a problem because a double can hold up to
so when you simply do
double d = 2147483648.0;
int example = (int)d;
you will again get
-2147483648
What you want
You want to use a type that supports larger numbers. Like e.g.
long: goes up to
9,223,372,036,854,775,807
and is actually what system time ticks are usually stored as (see e.g. DateTime.Ticks
or actually since your time is probably never negative anyway directly use the unsigned ones
ulong: goes up to
18,446,744,073,709,551,615
Solution
Long store short: There are implicit conversion for the other numeric values so all you need to do is use
ulong unixtimeOnline = itemsData2["lastUpdated"];
and it will use AsUlong instead
public static implicit operator ulong(JSONNode d)
{
return (d == null) ? 0 : d.AsULong;
}
which now correctly uses
public virtual ulong AsULong
{
get
{
ulong val = 0;
if (ulong.TryParse(Value, out val))
return val;
return 0;
}
set
{
Value = value.ToString();
}
}
As the comment says you will need to use a long variable type

Why is this method accepting byte, when it's parameter is double?

First, I want to say that this is just a simple code, it's an example and I am studying for a exam.
public class TOblik
{
public int povrsina = 0;
public TVrsta vrsta = 0;
public TOblik(TVrsta a)
{
}
}
public enum TVrsta
{
Kvadrat,
Krug
}
public class A
{
public static double Dodaj(TOblik o, TVrsta v, double r = 0)
{
if (v == TVrsta.Kvadrat)
{
return o.povrsina + r * r;
}
else
{
o.vrsta = v;
return o.povrsina;
}
}
static void Main(string[] args)
{
TOblik oblik = new TOblik(TVrsta.Kvadrat);
double vrednost = 10;
byte broj = 5;
TVrsta vrsta = TVrsta.Krug;
Dodaj(oblik, vrsta, broj);
Console.WriteLine();
Console.ReadLine();
}
}
What I don't get is why is this code working. The method Dodaj last parameter is double, but it is accepting when I forward broj (which type is byte).
C# has implicit casts: data of some types can convert to data in other types without mentioning the conversion (explicit conversions also exist like for instance byte a = (byte) b; ). Usually implicit casts can only be done when the "target type" is more general and thus can handle all values of the source type.
As you can read in the documentation:
The following table shows the predefined implicit numeric conversions.
Implicit conversions might occur in many situations, including method
invoking and assignment statements.
(...)
From To
------------------------------------------------------------------------
... ...
byte short, ushort, int, uint, long, ulong, float, double, or decimal
... ...
The documentation also warns that conversion from int to for instance float might result in precision loss. So one always has to be a bit careful with these.
You can see that this conversion happens in the csharp interactive shell:
csharp> byte a = 10;
csharp> double b = a;
csharp> b
10

How to get an exception on inaccurate calculation?

Every time we need a high decimal-precision, we use decimals to do the calculations. Is there any way to check if the precision did suffice for the calculation?
I would like to make the following code throw an exception:
decimal almostMax = Decimal.MaxValue - 1;
decimal x = almostMax + 0.1m; // This should create an exception, since x equals almostMax.
Assert.AreEqual(x, almostMax); // This does NOT fail.
It doesn't really matter in real code, but it would be nice to be safe.
This extension method should help. It reverses the operation and checks if the input arguments can be calculated correctly from the result. If that's not the case then the operation caused precision loss.
public static decimal Add(this decimal a, decimal b)
{
var result = a + b;
if (result - a != b || result - b != a)
throw new InvalidOperationException("Precision loss!");
return result;
}
Working example: https://dotnetfiddle.net/vx6UYY
If you want to use the regular operators like + etc, you have to go with Philipp Schmid's solution and implement the operators on your own decimal type.
You could make a SaveDecimal class and overload the + operator
https://msdn.microsoft.com/en-us/library/aa288467%28v=vs.71%29.aspx
public class SafeDecimal
{
private decimal DecValue;
public SafeDecimal(decimal Value)
{
DecValue = Value;
}
public decimal GetValue()
{
return DecValue;
}
public static SafeDecimal operator +(SafeDecimal A, SafeDecimal B)
{
decimal almostMax = Decimal.MaxValue - 1;
checked
{
if (almostMax <= A.GetValue() + B.GetValue())
throw new Exception("----scary error message----");
}
return new SafeDecimal(A.GetValue() + B.GetValue());
}
}

In a C# public method, what does the `int` indicate apart from the type integer?

In C#, when defining a public method like:
public int myMethod(String someString)
{
//code
}
What does the int indicate apart from the type integer? What confuses me is that the method is using a String as arguments in this case.
It is the return type of the method. In this case a 32-bit signed integer with a range of
-2,147,483,648 .. +2,147,483,647
It corresponds to the .NET type System.Int32. int is just a handy C# alias for it.
You would return a value like this
public int Square(int i)
{
return i * i;
}
And you could call it like this
int sqr = Square(7); // Returns 49
// Or
double d = Math.Sin(Square(3));
If you do not need the return value, you can safely ignore it.
int i;
Int32.TryParse("123", out i); // We ignore the `bool` return value here.
If you have no return value you would use the keyword void in place of the type. void is not a real type.
public void PrintSquare(int i)
{
Console.WriteLine(i * i);
}
And you would call it like this
PrintSquare(7);
The method in your example accepts a string as input parameter and returns an int as result. A practical example would be a method that counts the number of vowels in a string.
public int NumberOfVowels(string s)
{
const string vowels = "aeiouAEIOU";
int n = 0;
for (int i = 0; i < s.Length; i++) {
if (vowels.Contains(s[i])) {
n++;
}
}
return n;
}
It stands for "integer", and it means the method returns an integer number of 32 bits, also known in C# as Int32.
As previously stated, it's what the method returns.
For example:
public string x()
{
return 5;
}
Would error. 5 is definitely not a string!
public int x()
{
return 5;
}
Would be correct; since 5 can be considered an int (Short for integer, which is, basically, just a number which cannot have a decimal point. There's also float, double, long and decimal, which are worth reading about)
There must be no way of it not returning, for example, if you do:
public int x()
{
if (false)
{
return 5;
}
}
It will error because if the expression is false (It is of course) it won't be returning an int, it won't return anything.
If you use the keyword void, it means it does not return anything. Ex:
public void x()
{
someFunction("xyz");
}
It's fine that it doesn't return as it's a void method.
I don't think you're new to programming judging by your reputation, but just in case, when you return something you pass it back from the method, for example:
int x;
public int seven()
{
return 7;
}
x = seven();
x will become the return value of the function seven.
Note that the 'dynamic' type works here:
public dynamic x(int x, int y)
{
if (x == y)
{
return "hello";
}
return 5
}
But if you're new to C# don't get caught up in dynamic typing just yet. :)
It is the type of the return value.
Everyone is correct here but the definition from msdn:
"Int32 is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 (which is represented by the Int32.MinValue constant) through positive 2,147,483,647 (which is represented by the Int32.MaxValue constant. The .NET Framework also includes an unsigned 32-bit integer value type, UInt32, which represents values that range from 0 to 4,294,967,295."
Found here on MSDN: Int32 Structure
I suggest you read the documentation found in the link above. It is extremely useful.

Is it possible to write Quake's fast InvSqrt() function in C#?

This is just to satisfy my own curiosity.
Is there an implementation of this:
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
in C#? If it exists, post the code.
I guess I should have mentioned I was looking for a "safe" implementation... Either way, the BitConverter code solves the problem. The union idea is interesting. I'll test it and post my results.
Edit:
As expected, the unsafe method is the quickest, followed by using a union (inside the function), followed by the BitConverter. The functions were executed 10000000 times, and the I used the System.Diagnostics.Stopwatch class for timing. The results of the calculations are show in brackets.
Input: 79.67
BitConverter Method: 00:00:01.2809018 (0.1120187)
Union Method: 00:00:00.6838758 (0.1120187)
Unsafe Method: 00:00:00.3376401 (0.1120187)
For completeness, I tested the built-in Math.Pow method, and the "naive" method (1/Sqrt(x)).
Math.Pow(x, -0.5): 00:00:01.7133228 (0.112034710535584)
1 / Math.Sqrt(x): 00:00:00.3757084 (0.1120347)
The difference between 1 / Math.Sqrt() is so small that I don't think one needs to resort to the Unsafe Fast InvSqrt() method in C# (or any other unsafe method). Unless one really needs to squeeze out that last bit of juice from the CPU... 1/Math.Sqrt() is also much more accurate.
You should be able to use the StructLayout and FieldOffset attributes to fake a union for plain old data like floats and ints.
[StructLayout(LayoutKind.Explicit, Size=4)]
private struct IntFloat {
[FieldOffset(0)]
public float floatValue;
[FieldOffset(0)]
public int intValue;
// redundant assignment to avoid any complaints about uninitialized members
IntFloat(int x) {
floatValue = 0;
intValue = x;
}
IntFloat(float x) {
intValue = 0;
floatValue = x;
}
public static explicit operator float (IntFloat x) {
return x.floatValue;
}
public static explicit operator int (IntFloat x) {
return x.intValue;
}
public static explicit operator IntFloat (int i) {
return new IntFloat(i);
}
public static explicit operator IntFloat (float f) {
return new IntFloat(f);
}
}
Then translating InvSqrt is easy.
Use BitConverter if you want to avoid unsafe code.
float InvSqrt(float x)
{
float xhalf = 0.5f * x;
int i = BitConverter.SingleToInt32Bits(x);
i = 0x5f3759df - (i >> 1);
x = BitConverter.Int32BitsToSingle(i);
x = x * (1.5f - xhalf * x * x);
return x;
}
The code above uses new methods introduced in .NET Core 2.0. For .NET Framework, you have to fall back to the following (which performs allocations):
float InvSqrt(float x)
{
float xhalf = 0.5f * x;
int i = BitConverter.ToInt32(BitConverter.GetBytes(x), 0);
i = 0x5f3759df - (i >> 1);
x = BitConverter.ToSingle(BitConverter.GetBytes(i), 0);
x = x * (1.5f - xhalf * x * x);
return x;
}
Otherwise, the C# code is exactly the same as the C code you gave, except that the method needs to be marked as unsafe:
unsafe float InvSqrt(float x) { ... }
Definitely possible in unsafe mode. Note that even though in the Quake 3 source code the constant 0x5f3759df was used, numerical research showed that the constant 0x5f375a86 actually yields better results for Newton Approximations.
I don't see why it wouldn't be possible using the unsafe compiler option.

Categories