Moq - What is Range in It.IsInRange(TValue from, TValue to, Range rangeKind)? - moq

I've searched google for an explanation of what the Range parameter does but found nothing, so I'm putting my trust in you to explain what the difference is in setting Range.Inclusive or Range.Exclusive when using It.IsInRange(TValue from, TValue to, Range rangeKind)?

I do not know for sure, but I would assume that inclusive means that the values that you provide for the range are part of the range and exclusive means that they are not part of the range:
inclusive: lower bound <= x <= upper bound
exclusive: lower bound < x < upper bound

The Range (Enum) parameter as specified in the documentation -
Exclusive : The range does not include the to and from values.
Inclusive : The range includes the to and from values.
Usage as the answer demonstrates
It.IsInRange(0, 100, Range.Exclusive); // will not match for int values 0 and 100, but matches 1 to 99
and
It.IsInRange(0, 100, Range.Inclusive); // will match for int values 0 and 100, and in-between

Related

Does runif() really have a range: 0<= runif(n) <= 1, as stated in the documentation?

I'm new to R, but the documentation surprised me by stating that runif(n) returns a number in the range 0 to 1 inclusive.
I would expect 0 <= runif(n) < 1 -- including 0 and not including 1.
I tested it with n = 100,000,000, and found that it never produced 0 or 1. I realize that the probability of actually hitting specific values in floating point is really small, but still... (There are something like 2^53 values between 0 and 1 in double precision).
So I looked into the source code for R and found in r-source-trunk\src\nmath\runif.c
do
{
u = unif_rand();
} while (u <= 0 || u >= 1);
return a + (b - a) * u;
So by design, despite the documentation, it will never ever return a 0 or 1.
Isn't this a bug?
Or at least a problem with the documentation?
The underlying uniform random number function is defined here and the final outputs use this function:
static double fixup(double x)
{
/* ensure 0 and 1 are never returned */
if(x <= 0.0) return 0.5*i2_32m1;
if((1.0 - x) <= 0.0) return 1.0 - 0.5*i2_32m1;
return x;
}
Despite this, there are comments of the form /* in [0,1) */ for each of the generator's return functions, which I assume is a mistake given the above.
And of course, the code you noticed in runif.c is preceded by:
/* This is true of all builtin generators, but protect against
user-supplied ones */
So the min or max will never be returned except in the cases mentioned by #JesseTweedle, which is not the case when just calling runif().
For reference, the magic value i2_32m1 is 1/(2^32-1) so the minimum value you can get from the default generators is 1/(2^33-2) which is approximately 1.16e-10. The maximum value is this amount short of 1.
The documentation says:
runif will not generate either of the extreme values unless max = min
or max-min is small compared to min, and in particular not for the
default arguments.
With default arguments, the documentation is consistent with the behaviour you see.

Find max value of X that satisfies both 9x < 10 && 7.5x < 8

I am writing a program that needs to find the maximum value of X that satisfies the 2 following equations:
9x < 10
7.5x < 8
Can anyone advise on the best way to go about this? I am writing the program in Dart but would appreciate examples/advice in any language.
This is what I have done currently but I am not 100% sure this is correct:
double Xval = 10/9;
if(7.5 * Xval > 8)
Xval = 8 / 7.5;
Please note the program would have to work if we changed any or all of the numbers (e.g. the 9, 10, 7.5 or the 8).
It needs some mathematical logic.
1)First find value of x by replacing < to =. Eg. Find x in 9x=10.
2)Find minimum of both the solution x.
3)This minimum value will satisfy both the equation its obvious but we have replaced < with = so we need to subtract a smallest value by which we can find maximum x which satisfy the original equation.
4)So subtract the value 0.0001 from minimum if you want 4 decimal point precision. Generally subtract (10)^(-DecimalPointPrecision) value ,so here DecimalPointPrecision is equal to 4.
5)This value you get will satisfy both the equation and it will be the maximum value of x.
I have written a code in java implementing this logic.
import java.util.Scanner;
class SolveEquation
{
public static void main(String [] args)
{
float ip1_left;
float ip1_right;
float ip2_left;
float ip2_right;
Scanner sc=new Scanner(System.in);
System.out.print("\nEnter the multiplier of x of 1st equation:");
ip1_left=sc.nextFloat();
System.out.print("Enter the constant of 1st equation:");
ip1_right=sc.nextFloat();
System.out.print("Enter the multiplier of x of 2nd equation:");
ip2_left=sc.nextFloat();
System.out.print("Enter the constant of x of 2nd equation:");
ip2_right=sc.nextFloat();
float ans1=ip1_right/ip1_left;
float ans2=ip2_right/ip2_left;
float min=ans1;
if(ans2<ans1)
min=ans2;
//If you want 4 decimal precision then print 4 digits after point and subtract 0.0001 (where 1 is placed on 4th place after decimal point).
System.out.printf("\nMaximum value of x is %.4f",min-0.0001);
}
}
Sample output for input as per your question:

Number of Zero-crossings - Equation

I have written an algorithm that calculates the number of zero-crossings within a signal. By this, I mean the number of times a value changes from + to - and vice-versa.
The algorithm is explained like this:
If there are the following elements:
v1 = {90, -4, -3, 1, 3}
Then you multiply the value by the value next to it. (i * i+1)
Then taking the sign value sign(val) determine if this is positive or negative. Example:
e1 = {90 * -4} = -360 -> sigum(e1) = -1
e2 = {-4 * -3} = 12 -> signum(e2) = 1
e3 = {-3 * 1} = -3 -> signum(e3) = -1
e4 = {1 * 3} = 3 -> signum(e4) = 1
Therefore the total number of values changed from negative to positive is = 2 ..
Now I want to put this forumular, algorithm into an equation so that I can present it.
I have asked a simular question, but got really confused so went away and thought about it and came up with (what I think the equation should look like).. It's probably wrong, well, laughably wrong. But here it is:
Now the logic behind it:
I pass in a V (val)
I get the absolute value of the summation of the signum from calculating (Vi * Vi+1) .. The signum(Vi * Vi+1) should produce -1, 1, ..., values
If and only if the value is -1 (Because I'm only interested in the number of times zero is crossed, therefore, the zero values.
Does this look correct, if not, can anyone suggest improvements?
Thank you :)!
EDIT:
Is this correct now?
You are doing the right thing here but your equation is wrong simply because you only want to count the sign of the product of adjacent elements when it is negative. Dont sum the sign of products since positive sign products should be neglected. For this reason, an explicit mathematical formula is tricky as positive products between adjacent elements should be ignored. What you want is a function that takes 2 arguments and evaluates to 1 when their product is negative and zero when non-negative
f(x,y) = 1 if xy < 0
= 0 otherwise
then your number of crossing points is simply given by
sum(f(v1[i],v1[i+1])) for i = 0 to i = n-1
where n is the length of your vector/array v1 (using C style array access notation based on zero indexing). You also have to consider edge conditions such as 4 consecutive points {-1,0,0,1} - do you want to consider this as simply one zero crossing or 2??? Only you can answer this based on the specifics of your problem, but whatever your answer adjust your algorithm accordingly.

How to efficiently convert a few bytes into an integer between a range?

I'm writing something that reads bytes (just a List<int>) from a remote random number generation source that is extremely slow. For that and my personal requirements, I want to retrieve as few bytes from the source as possible.
Now I am trying to implement a method which signature looks like:
int getRandomInteger(int min, int max)
I have two theories how I can fetch bytes from my random source, and convert them to an integer.
Approach #1 is naivé . Fetch (max - min) / 256 number of bytes and add them up. It works, but it's going to fetch a lot of bytes from the slow random number generator source I have. For example, if I want to get a random integer between a million and a zero, it's going to fetch almost 4000 bytes... that's unacceptable.
Approach #2 sounds ideal to me, but I'm unable come up with the algorithm. it goes like this:
Lets take min: 0, max: 1000 as an example.
Calculate ceil(rangeSize / 256) which in this case is ceil(1000 / 256) = 4. Now fetch one (1) byte from the source.
Scale this one byte from the 0-255 range to 0-3 range (or 1-4) and let it determine which group we use. E.g. if the byte was 250, we would choose the 4th group (which represents the last 250 numbers, 750-1000 in our range).
Now fetch another byte and scale from 0-255 to 0-250 and let that determine the position within the group we have. So if this second byte is e.g. 120, then our final integer is 750 + 120 = 870.
In that scenario we only needed to fetch 2 bytes in total. However, it's much more complex as if our range is 0-1000000 we need several "groups".
How do I implement something like this? I'm okay with Java/C#/JavaScript code or pseudo code.
I'd also like to keep the result from not losing entropy/randomness. So, I'm slightly worried of scaling integers.
Unfortunately your Approach #1 is broken. For example if min is 0 and max 510, you'd add 2 bytes. There is only one way to get a 0 result: both bytes zero. The chance of this is (1/256)^2. However there are many ways to get other values, say 100 = 100+0, 99+1, 98+2... So the chance of a 100 is much larger: 101(1/256)^2.
The more-or-less standard way to do what you want is to:
Let R = max - min + 1 -- the number of possible random output values
Let N = 2^k >= mR, m>=1 -- a power of 2 at least as big as some multiple of R that you choose.
loop
b = a random integer in 0..N-1 formed from k random bits
while b >= mR -- reject b values that would bias the output
return min + floor(b/m)
This is called the method of rejection. It throws away randomly selected binary numbers that would bias the output. If min-max+1 happens to be a power of 2, then you'll have zero rejections.
If you have m=1 and min-max+1 is just one more than a biggish power of 2, then rejections will be near half. In this case you'd definitely want bigger m.
In general, bigger m values lead to fewer rejections, but of course they require slighly more bits per number. There is a probabilitistically optimal algorithm to pick m.
Some of the other solutions presented here have problems, but I'm sorry right now I don't have time to comment. Maybe in a couple of days if there is interest.
3 bytes (together) give you random integer in range 0..16777215. You can use 20 bits from this value to get range 0..1048575 and throw away values > 1000000
range 1 to r
256^a >= r
first find 'a'
get 'a' number of bytes into array A[]
num=0
for i=0 to len(A)-1
num+=(A[i]^(8*i))
next
random number = num mod range
Your random source gives you 8 random bits per call. For an integer in the range [min,max] you would need ceil(log2(max-min+1)) bits.
Assume that you can get random bytes from the source using some function:
bool RandomBuf(BYTE* pBuf , size_t nLen); // fill buffer with nLen random bytes
Now you can use the following function to generate a random value in a given range:
// --------------------------------------------------------------------------
// produce a uniformly-distributed integral value in range [nMin, nMax]
// T is char/BYTE/short/WORD/int/UINT/LONGLONG/ULONGLONG
template <class T> T RandU(T nMin, T nMax)
{
static_assert(std::numeric_limits<T>::is_integer, "RandU: integral type expected");
if (nMin>nMax)
std::swap(nMin, nMax);
if (0 == (T)(nMax-nMin+1)) // all range of type T
{
T nR;
return RandomBuf((BYTE*)&nR, sizeof(T)) ? *(T*)&nR : nMin;
}
ULONGLONG nRange = (ULONGLONG)nMax-(ULONGLONG)nMin+1 ; // number of discrete values
UINT nRangeBits= (UINT)ceil(log((double)nRange) / log(2.)); // bits for storing nRange discrete values
ULONGLONG nR ;
do
{
if (!RandomBuf((BYTE*)&nR, sizeof(nR)))
return nMin;
nR= nR>>((sizeof(nR)<<3) - nRangeBits); // keep nRangeBits random bits
}
while (nR >= nRange); // ensure value in range [0..nRange-1]
return nMin + (T)nR; // [nMin..nMax]
}
Since you are always getting a multiple of 8 bits, you can save extra bits between calls (for example you may need only 9 bits out of 16 bits). It requires some bit-manipulations, and it is up to you do decide if it is worth the effort.
You can save even more, if you'll use 'half bits': Let's assume that you want to generate numbers in the range [1..5]. You'll need log2(5)=2.32 bits for each random value. Using 32 random bits you can actually generate floor(32/2.32)= 13 random values in this range, though it requires some additional effort.

How do I normalize an image?

If I have a series of pixels, which range from say -500 to +1000, how would I normalize all the pixels on the same gradient so that they fall between a specific range, say 0 and 255?
Some pseudocode like this would scale values linearly from one range to another
oldmin=-500
oldmax=1000
oldrange=oldmax-oldmin;
newmin=0
newmax=255;
newrange=newmax-newmin;
foreach(oldvalue)
{
//where in the old scale is this value (0...1)
scale=(oldvalue-oldmin)/oldrange;
//place this scale in the new range
newvalue=(newrange*scale)+newmin
}
Your question isn't very clear so I'm going to assume that you're doing some kind of image processing and the results you get are values from -500 to 1000 and now you need to save the color to a file where every value needs to be between 0 and 255.
How you do this is really very dependent in the application, what is really the meaning of the results and what exactly you want to do. The two main options are:
clamp the values - anything under 0 you replace by 0 and anything above 255 you replace by 255. You'll want to do this, for instance, if your image processing is some kind of interpolation which really shouldn't reach these values
Linear normalization - linearly may your minimal value to 0 and your maximal value to 255. Of course you'll first need to find the minimum and maximum. You do:
v = (origv - min)/(max - min) * 255.0
What this does is first map the values to [0,1] and then stretch them back to [0,255].
A third option is to mix and match between these two options. Your application might demand that you treat negative values as unneeded values and clamp them to 0 and positive values to linearly map to [0,255].
First make it all positive. If the minimum is -500 then add 500 to all values. Then the minimum would be 0, and the maximum would be 1500.
Then it is just a rule of three and you have it:
[value in 0,255] = 255*(Pixel/1500)
Some pseudo code may help:
foreach( pixel_value in pixel_values): # between -500 and 1000
position = (pixel_value + 500) / 1500 # gives you a 0 to 1 decimal
new_value = int(postion * 255) # or instead of casting, you could round it off
That's python code by the way.
Create two variables, MinInputValue and MaxInputValue. Initialize MinInputValue to a very large positive number (higher than the largest pixel value you ever expect to see) and MaxInputValue to a very large negative number (lower than the lowest pixel value you ever expect to see).
Loop over every pixel in the image. For each pixel, if the pixel value PixelValue is lower than MinInputValue, set MinInputValue to PixelValue. If the pixel value is higher than MaxInputValue, set MaxInputValue to PixelValue.
Create a new variable, InputValueRange, and set it to MaxInputValue - MinInputValue.
Once this is done, loop over every pixel in the image again. For each pixel PixelValue, calculate the output pixel value as 255.0 * (PixelValue - MinInputValue) / InputValueRange. You can assign this new value back to the original PixelValue, or you can set the corresponding pixel in an output image of the same size.

Resources