C# function to find the delta of two numbers [duplicate] - c#

This question already has answers here:
Difference between 2 numbers
(6 answers)
Closed 5 years ago.
I just wanted to know if there's anything built into the .net framework where I can easily return the delta between two numbers? I wrote code that does this but it sounds like something that should be in the framework already.

delta = Math.Abs(a - b);

I'm under the impression that "delta" is the difference between two numbers.
Until you tell me differently, I think what you want is:
delta = Math.Abs(a - b);

public static int Delta(int a, int b)
{
int delta = 0;
if (a == b)
{
return 0;
}
else if (a < b)
{
while (a < b)
{
a++;
delta++;
}
return delta;
}
else
{
while (b < a)
{
b++;
delta++;
}
return delta;
}
}
:p
Oh boy, I hope no (future) employer comes across this and stops reading in disgust before he reaches the end of this post..

The Linq version (requires CLR 4.0).
(cracks fingers, clears throat)
var delta = (from t in Enumerable.Range(a, a).Zip(Enumerable.Range(b, b))
select Math.Abs(t.Item1 - t.Item2))
.First();

Isn't that what the minus operator does? :p

public static int Delta(int a, int b)
{
return a > 0? Delta(a-1, b-1) : a < 0 ? Delta(a+1, b+1) : b > 0 ? b : -b;
}
I think that's even better than #JulianR Delta implementation :-p
Edit: I didn't realize that this was already suggested by #Robert Harvey, credit to him ;-)

What is the delta of two numbers?
Delta has a certain meaning in set-theory and infinitesimal calculus, but this doesn't refer to numbers!
If you want to calculate the difference between two numbers a and b, you write |a - b| which is Math.Abs(a - b) in C#.

I decided to revise JulianR's funny answer above.
The code is shorter, but perhaps more tricky:
public static int Delta(int a, int b)
{
int delta = 0;
while (a < b)
{
++a;
++delta;
}
while (b < a)
{
++b;
++delta;
}
return delta;
}
(for the humor-impaired.... this is no more serious than the bizarre question that started the thread)

(r1+r2)/2
Avarage between two numbers.

Related

Multiply by 27 using only bit shifting, addition and subtraction as few times as possible

I recently had a C# technical assessment for a job application where one of the questions was:
Question 11: Implement the function int Mult27(int a) such that it returns the result of a multiplied by 27. Do so using only the following functions (provided):
SHL(a,b) shifts all the bits of integer a left by b places.
ADD(a,b) adds two integers giving a+b.
SUB(a, b) subtracts two integers to give a-b.
Do so using as few calls to these functions as possible, assume a is always a positive integer.
public class AnswerEleven
{
int SHL(int a, int b)
{
return a << b;
}
int ADD(int a, int b)
{
return a + b;
}
int SUB(int a, int b)
{
return a - b;
}
public int Mult27(int a)
{
}
}
I'm pretty sure I wasn't allowed to use operators like %, and I couldn't use string conversions or other types. I couldn't think of how to do it other than bit shifting to the left to get the power of 2 (which only solves by powers of 2) or using division by two and the subtraction method (which doesn't help). But it seems like there may be multiple ways to solve the problem.
I ended up submitting without being able to finish the problem and it's been bothering me that I can't find an answer without using a typical but not allowed method. Any ideas?
Deconstructing integers into powers of 2 can be done in various ways. Here is a simple one:
27x = 32x - 5x = 32x - 4x - x
Hence you can write
public int Mult27(int a)
{
return SUB(SUB(SHL(a, 5), SHL(a, 2)), a);
}
This uses only four calls to your allowed functions. Hard to top I believe..
How about this:
public int Mult27(int a)
{
return ADD(ADD(SHL(a, 4), SHL(a, 3)), SUB(SHL(a, 2), a));
}
var ae = new AnswerEleven();
Console.WriteLine(ae.Mult27(1));
Console.WriteLine(ae.Mult27(2));
That gives 27 and 54.
public int Mult27(int a)
{
a = ADD(a, SHL(a, 1)); // or SUB(SHL(a, 2), a) → a = 3a
return ADD(a, SHL(a, 3)); // 3a + 8*3a = 27a
}
This has the nice property that it avoids the overflow when shifting by 5 like when expanding 27x = 32x - 5x
Here's an alternate version that also uses 4 calls
int a4 = SHL(a, 2); // a4 = a*4
return SUB(SUB(SHL(a4, 3), a4), a); // a4*8 - a4 - a

How would I create my own test case to figure out why this code returns the correct answer half of the time?

I'm trying to figure out why if I change my values from 4 & 2 to something like 4 & 3, it doesn't compute the averages correctly.
I would like to know 2 things.
How to run a testcase for something as simple as this, and how to fix my code to where it will average out two numbers correctly every time.
using System;
public class MathUtils
{
public static double Average(int a, int b)
{
return (a + b) / 2;
}
public static void Main(string[] args)
{
Console.WriteLine(Average(4, 2));
}
}
// right now returns 3 which is correct
Change it to :
public static double Average(int a, int b)
{
return (a + b) / 2.0; // will be incorrect for edge case with int-overflow - see Edit
}
Reason:
If you add up two integers you get an integer. If you divide an integer by an integer you get another integer by default - not a float or double. The parts after the . are discarded.
Edit:
As Hans Passant pointed out, you can get an overflow error in case both ints add up to more than a int can handle - so casting (at least one of) them to double is the smarter move
return ((double)a + b) / 2; // .0 no longer needed.
You need to get some non-integers in the mix to get the .xxxx part as well.
As for the testcase - that depends on the testing framework you are using.
You should probably consider testcases of (int.MinValue, int.Minvalue) , (int.MaxValue, int.MaxValue) and some easy ones (0,0), (1,1), (1,2)
For how to detect the error: get some C# experience - or use intermediate variables and breakpoints and a debugger to see what goes wrong where.
This here:
public static double Average(int a, int b)
{
var summed = a + b;
var avg = summed / 2;
return avg;
}
in debugging would point out the error quite fast.
return ((double)a + b) / 2; //simple

Re-writing code to remove conditional statements

Is it possible to re-write the following so that it doesn't contain any conditional statements? I'm thinking there might be some clever trick using something like bitwise operations?
int a = // some value
int b = // some other value between 0 and max int
if(b >= 3)
{
return a + 1;
}
else
{
return a;
}
EDIT: to be clear, I'm not looking for a generic way of removing conditionals. I'm looking for a trick to remove the conditionals from this very specific code. Think of it as an academic puzzle.
To give an example, one way to remove conditionals (which happens to yield perf gains in some situations) is to precompute a lookup table and index into that with b instead. In this particular case this is tricky because b could be a very large number. Is there another way?
Here you go
return a - ((2 - b) >> 31);
Explanation:
r = 2 - b, < 0 (i.e. high bit set) for b >= 3
r >> 31, = -1 for b >= 3, 0 otherwise
uint a = // some value
uint b = // some other value between 0 and max int
bool c = b & 0xFFFC
return a + Convert.ToInt32(c);
The fastest will probably be as bitwise operations tend to be very fast
uint a = // some value
uint b = // some other value between 0 and max int
return (b & 0xFFFC) ? a+1 : a;
You could make it better by doing this:
int a = // some value
int b = // some other value between 0 and max int
return (b >= 3) ? (a+1) : a;
?: operator. (but yet it contains conditional statement.)
return b >= 3 ? a + 1 : a;
or
return a + (b >= 3 ? 1 : 0);
Is it possible to re-write the following so that it doesn't contain any conditional statements?
It is not possible to make it work out of no where. you must check this condition any way. There is no magic.
If you want to make your program faster by removing this condition then you picked wrong way. this is micro optimization.

Floored integer division

Is there an easy, efficient and correct (i.e. not involving conversions to/from double) way to do floored integer division (like e.g. Python offers) in C#.
In other words, an efficient version of the following, that does not suffer from long/double conversion losses.
(long)(Math.Floor((double) a / b))
or does one have to implement it oneself, like e.g.
static long FlooredIntDiv(long a, long b)
{
if (a < 0)
{
if (b > 0)
return (a - b + 1) / b;
// if (a == long.MinValue && b == -1) // see *) below
// throw new OverflowException();
}
else if (a > 0)
{
if (b < 0)
return (a - b - 1) / b;
}
return a / b;
}
*) Although the C# 4 spec of the Division operator leaves it open whether OverflowException is raised inside unchecked, in reality it does throw (on my system) and the Visual Studio .NET 2003 version even mandated it throw:
If the left operand is the smallest representable int or long value and the right operand is –1, [..] System.OverflowException is always thrown in this situation, regardless of whether the operation occurs in a checked or an unchecked context.
Edit
The crossed out statements about checked and unchecked are all nice and well, but checked is in fact only a compile time concept, so whether my function should wrap around or throw is up to me anyway, regardless of whether code calling the function is inside checked or not.
You can try this:
if (((a < 0) ^ (b < 0)) && (a % b != 0))
{
return (a/b - 1);
}
else
{
return (a/b);
}
Edit (after some discussions in comments below):
Without using if-else, I would go like this:
return (a/b - Convert.ToInt32(((a < 0) ^ (b < 0)) && (a % b != 0)));
Note: Convert.ToIn32(bool value) also needs a jump, see implemention of the method:
return value? Boolean.True: Boolean.False;
Theoretically, it is not possible to calculate the division for a = long.MinValue and b = -1L, since the expected result is a/b = abs(long.MinValue) = long.MaxValue + 1 > long.MaxValue. (Range of long is –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.)
The way it works in any sane programming language (one that follows our normal order of operations) is that -1.0/3.0 is equivalent to -(1.0/3.0) which is -0.3333.... So if you want that converted to an int, it's really the cast/floor operator you need to think about, not the division. As such, if you want this behavior, you must use (int)Math.Floor(a/b), or custom code.
You don't need to implement this yourself, the Math class provides a builtin method for doing Euclidean division: Math.DivRem()
The only downside is that you have to provide an assignable variable for the remainder:
long remainder;
long quotient = Math.DivRem(a, b, out remainder);

How is Math.Pow() implemented in .NET Framework?

I was looking for an efficient approach for calculating ab (say a = 2 and b = 50). To start things up, I decided to take a look at the implementation of Math.Pow() function. But in .NET Reflector, all I found was this:
[MethodImpl(MethodImplOptions.InternalCall), SecuritySafeCritical]
public static extern double Pow(double x, double y);
What are some of the resources wherein I can see as what's going on inside when I call Math.Pow() function?
MethodImplOptions.InternalCall
That means that the method is actually implemented in the CLR, written in C++. The just-in-time compiler consults a table with internally implemented methods and compiles the call to the C++ function directly.
Having a look at the code requires the source code for the CLR. You can get that from the SSCLI20 distribution. It was written around the .NET 2.0 time frame, I've found the low-level implementations, like Math.Pow() to be still largely accurate for later versions of the CLR.
The lookup table is located in clr/src/vm/ecall.cpp. The section that's relevant to Math.Pow() looks like this:
FCFuncStart(gMathFuncs)
FCIntrinsic("Sin", COMDouble::Sin, CORINFO_INTRINSIC_Sin)
FCIntrinsic("Cos", COMDouble::Cos, CORINFO_INTRINSIC_Cos)
FCIntrinsic("Sqrt", COMDouble::Sqrt, CORINFO_INTRINSIC_Sqrt)
FCIntrinsic("Round", COMDouble::Round, CORINFO_INTRINSIC_Round)
FCIntrinsicSig("Abs", &gsig_SM_Flt_RetFlt, COMDouble::AbsFlt, CORINFO_INTRINSIC_Abs)
FCIntrinsicSig("Abs", &gsig_SM_Dbl_RetDbl, COMDouble::AbsDbl, CORINFO_INTRINSIC_Abs)
FCFuncElement("Exp", COMDouble::Exp)
FCFuncElement("Pow", COMDouble::Pow)
// etc..
FCFuncEnd()
Searching for "COMDouble" takes you to clr/src/classlibnative/float/comfloat.cpp. I'll spare you the code, just have a look for yourself. It basically checks for corner cases, then calls the CRT's version of pow().
The only other implementation detail that's interesting is the FCIntrinsic macro in the table. That's a hint that the jitter may implement the function as an intrinsic. In other words, substitute the function call with a floating point machine code instruction. Which is not the case for Pow(), there is no FPU instruction for it. But certainly for the other simple operations. Notable is that this can make floating point math in C# substantially faster than the same code in C++, check this answer for the reason why.
By the way, the source code for the CRT is also available if you have the full version of Visual Studio vc/crt/src directory. You'll hit the wall on pow() though, Microsoft purchased that code from Intel. Doing a better job than the Intel engineers is unlikely. Although my high-school book's identity was twice as fast when I tried it:
public static double FasterPow(double x, double y) {
return Math.Exp(y * Math.Log(x));
}
But not a true substitute because it accumulates error from 3 floating point operations and doesn't deal with the weirdo domain problems that Pow() has. Like 0^0 and -Infinity raised to any power.
Hans Passant's answer is great, but I would like to add that if b is an integer, then a^b can be computed very efficiently with binary decomposition. Here's a modified version from Henry Warren's Hacker's Delight:
public static int iexp(int a, uint b) {
int y = 1;
while(true) {
if ((b & 1) != 0) y = a*y;
b = b >> 1;
if (b == 0) return y;
a *= a;
}
}
He notes that this operation is optimal (does the minimum number of arithmetic or logical operations) for all b < 15. Also there is no known solution to the general problem of finding an optimal sequence of factors to compute a^b for any b other than an extensive search. It's an NP-Hard problem. So basically that means that the binary decomposition is as good as it gets.
If freely available C version of pow is any indication, it does not look like anything you would expect. It would not be of much help to you to find the .NET version, because the problem that you are solving (i.e. the one with integers) is orders of magnitudes simpler, and can be solved in a few lines of C# code with the exponentiation by squaring algorithm.
Going through the answers, learned a lot about behind-the-scene calculations:
I've tried some workarounds on a coding platform which has an extensive test coverage cases, and found a very effective way doing it(Solution 3):
public double MyPow(double x, int n) {
double res = 1;
/* Solution 1: iterative : TLE(Time Limit Exceeded)
double res = 1;
var len = n > 0 ? n : -n;
for(var i = 0; i < len; ++i)
res *= x;
return n > 0 ? res : 1 / res;
*/
/* Solution 2: recursive => stackoverflow exception
if(x == 0) return n > 0 ? 0 : 1 / x;
if(n == 1) return x;
return n > 0 ? x * MyPow(x, n - 1) : (1/x) * MyPow(1/x, -n);
*/
//Solution 3:
if (n == 0) return 1;
var half = MyPow(x, n / 2);
if (n % 2 == 0)
return half * half;
else if (n > 0)
return half * half * x;
else
return half * half / x;
/* Solution 4: bitwise=> TLE(Time Limit Exceeded)
var b = n > 0 ? n : -n;
while(true) {
if ((b & 1) != 0)
res *= x;
b = b >> 1;
if (b == 0) break;
x *= x;
}
return n > 0 ? res : 1 / res;
*/
}
Answer that is accepted on Leetcode:
public class Solution {
public double MyPow(double x, int n) {
if(n==0) return 1;
long abs = Math.Abs((long)n);
var result = pow(x, abs);
return n > 0 ? result : 1/result;
}
double pow(double x, long n){
if(n == 1) return x;
var result = pow(x, n/2);
result = result * result * (n%2 == 1? x : 1);
return result;
}
}

Categories