I wanted to create a simple program which would generate random numbers between 0 and 1.
double x2, x3, z0, z1;
int i = 0;
double x0 = 0.3453;
double x1 = 0.3894;
for (i = 0; i < 50; i++)
{
x2 = (x0 + x1)%1.0;
x3 = (x1 + x2)%1.0;
[...]
There is something wrong with line "x2 = ..." and "x3 = ..."
I'm getting an error: "invalid operands of types 'double' and 'double' to binary 'operator%'
the % modulo operator is for integer values only. If you want to take the modulo of floating point values, you have to use fmod() instead
Related
I'm trying to identify bimodal distributions in my analytical chemistry data. Each data set is a list of 3~70 retention times for a particular compound from the GC-MS. RTs for some compound are bimodally distributed where the library searches have assigned the same identity to two or more different features in the data with different RTs. This is quite common for isomers and other compound pairs with very similar mass spectra.
Eg. here's a histogram of RTs for one compound showing bimodal distribution.
I want to calculate the Otsu threshold to try and define bimodal data (there's also multimodal distributions but one step at a time). I'm struggling to understand the Wikipedia article on the calculations but the text indicates that the threshold can be found by finding the minimum intraclass variance. So I've tried computing this from a list of the RTs as follows:
a = list(d['Component RT'])
n = len(a)
b = [a.pop(0)]
varA = []
varB = []
for i in range(1,n-2):
b.append(a.pop(0))
varA.append(statistics.stdev(a)**2)
varB.append(statistics.stdev(b)**2)
Am I right in thinking that if I plot the sum of the variances for the above data I should be able to identify the Otsu threshold as the minimum?
In this example the threshold is obvious and there's about 35 values to work from. For most compounds there's fewer values (typically <15) and the data may be less well defined. Is this even the right threshold to use? The Wikipedia article on modality indicates a whole bunch of other tests for multimodality.
result is simillar to opencv thresh by OTSU.
uchar OTSU(const std::vector<uchar>& input_vec) {
// normalize input to 0-255 if needed
int count[256];
double u0, u1, u;
double pixelSum0, pixelSum1;
int n0, n1;
int bestThresold = 0, thresold = 0;
double w0, w1;
double variable = 0, maxVariable = 0;
for (int i = 0; i < 256; i++)
count[i] = 0;
for (int i = 0; i < input_vec.size(); i++) {
count[int(input_vec[i])] ++;
}
for (thresold = 0; thresold < 256; thresold++) {
n0 = 0;
n1 = 0;
w0 = 0;
w1 = 0;
pixelSum0 = 0;
pixelSum1 = 0;
for (int i = 0; i < thresold; i++) {
n0 += count[i];
pixelSum0 += i * count[i];
}
for (int i = thresold; i < 256; i++) {
n1 += count[i];
pixelSum1 += i * count[i];
}
w0 = double(n0) / (input_vec.size());
w1 = double(n1) / (input_vec.size());
u0 = pixelSum0 / n0;
u1 = pixelSum1 / n1;
u = u0 * w0 + u1 * w1;
variable = w0 * pow((u0 - u), 2) + w1 * pow((u1 - u), 2);
if (variable > maxVariable) {
maxVariable = variable;
bestThresold = thresold;
}
}
return bestThresold;}
ref :https://github.com/1124418652/edge_extract/blob/master/edge_extract/OTSU.cpp
Let's say I have some number of different colored balls. For the sake of an example, let's assume 4 red balls, 4 blue balls and 2 green balls. If I want to evenly distribute these balls so that the most consistent distance between two balls of the same color is maintained I could have the following sequence:
R-B-G-R-B-R-B-G-R-B
Even though Blue and Red Balls aren't always the same distance from their counterparts, they are arranged in such a way that keeps their distances consistent while also maintaining consistency for the Green Balls
In the case of 6 red balls, 5 blue balls, and 3 green balls, I could have something like:
R-B-R-G-B-R-B-G-R-B-R-G-R
I'm not exactly sure what the criteria for "most consistent distance between two balls of the same color" would be but is there some kind of algorithm or generalized solution that would solve this? What is the formal name of this problem, if this is the case?
This problem is similar to drawing of line in nD-space (here 3D). So you can use Bresenham/DDA-like algorithms to generate sequence with fair item distribution (instead of fair distribution of pixel shifts in ever dimension). Arbitrary found example
(I have not checked its correctness - perhaps division dm/2 might produce worse results than error doubling):
void plotLine3d(int x0, int y0, int z0, int x1, int y1, int z1)
{
int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1;
int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1;
int dz = abs(z1-z0), sz = z0<z1 ? 1 : -1;
int dm = max(dx,dy,dz), i = dm; /* maximum difference */
x1 = y1 = z1 = dm/2; /* error offset */
for(;;) { /* loop */
setPixel(x0,y0,z0);
if (i-- == 0) break;
x1 -= dx; if (x1 < 0) { x1 += dm; x0 += sx; }
y1 -= dy; if (y1 < 0) { y1 += dm; y0 += sy; }
z1 -= dz; if (z1 < 0) { z1 += dm; z0 += sz; }
}
}
Replace x1-x0 by the first color count, y1-y0 by the second and so on. Output corresponding color in successful if-conditions:
{x1 -= dx; if (x1 < 0) { x1 += dm; x0 += sx;HERE}
Suppose I needed to solve the following equation,
ax + by = c
Where a, b, and c are known values and x, y are natural numbers between 0 and 10 (inclusively).
Other than the trivial solution of,
for (x = 0; x <= 10; x++)
for (y = 0; y <= 10; y++)
if (a * x + b * y == c)
printf("%d %d", x, y);
... is there any way to find all solutions for this independent system efficiently?
In your case, since x and y only take values between 0 and 10, brute force algorithm maybe the best option as it takes less time to implement.
However, if you have to find all pairs of integral solution (x, y) in a larger range, you really should apply the right mathematical tool for tackling this problem.
You are trying to solve a linear Diophantine equation, and it is well known that integral solution exists if and only if the greatest common divisor d of a and b divides c.
If solution does not exist, then you are done. Otherwise, you should first apply the Extended Euclidean Algorithm to find a paritcular solution for the equation ax + by = d.
And according to Bézout's identity, all other integral solutions are of the form:
where k is an arbitrary integer.
But note that we are interested in the solution of ax + by = c, we have to scale all our pairs of (x, y) by a factor of c / d.
You only to loop thru x, then calculate y. (x, y) is a solution if y is integer, and between 0 and 10.
In C:
for (int x = 0; x <= 10; ++x) {
double y = (double)(c - ax) / b;
// If y is an integer, and it's between 0 and 10, then (x, y) is a solution
BOOL isInteger = abs(floor(y) - y) < 0.001;
if (isInteger && 0 <= y && y <= 10) {
printf("%d %d", x, y);
}
}
You could avoid the second for loop by checking directly if (c-a*x)/b is an integer.
EDIT: My code is less clean than I had hoped, due to some careless oversights on my part pointed out in the comments, but it is still faster than nested for loops.
int by;
for (x = 0; x <= 10; x++) {
by = c-a*x; // this is b*y
if(b==0) { // check for special case of b==0
if (by==0) {
printf("%d and any value for y", x);
}
} else { // b!=0 case
y = by/b;
if (by%b==0 && 0<=y && y<=10) { // is y an integer between 0 and 10?
printf("%d %d", x, by/b);
}
}
}
I am trying to do bit reversal in a byte. I use the code below
static int BitReversal(int n)
{
int u0 = 0x55555555; // 01010101010101010101010101010101
int u1 = 0x33333333; // 00110011001100110011001100110011
int u2 = 0x0F0F0F0F; // 00001111000011110000111100001111
int u3 = 0x00FF00FF; // 00000000111111110000000011111111
int u4 = 0x0000FFFF;
int x, y, z;
x = n;
y = (x >> 1) & u0;
z = (x & u0) << 1;
x = y | z;
y = (x >> 2) & u1;
z = (x & u1) << 2;
x = y | z;
y = (x >> 4) & u2;
z = (x & u2) << 4;
x = y | z;
y = (x >> 8) & u3;
z = (x & u3) << 8;
x = y | z;
y = (x >> 16) & u4;
z = (x & u4) << 16;
x = y | z;
return x;
}
It can reverser the bit (on a 32-bit machine), but there is a problem,
For example, the input is 10001111101, I want to get 10111110001, but this method would reverse the whole byte including the heading 0s. The output is 10111110001000000000000000000000.
Is there any method to only reverse the actual number? I do not want to convert it to string and reverser, then convert again. Is there any pure math method or bit operation method?
Best Regards,
Get the highest bit number using a similar approach and shift the resulting bits to the right 33 - #bits and voila!
Cheesy way is to shift until you get a 1 on the right:
if (x != 0) {
while ((x & 1) == 0) {
x >>= 1;
}
}
Note: You should switch all the variables to unsigned int. As written you can have unwanted sign-extension any time you right shift.
One method could be to find the leading number of sign bits in the number n, left shift n by that number and then run it through your above algorithm.
It's assuming all 32 bits are significant and reversing the whole thing. You COULD try to make it guess the number of significant bits by finding the highest 1, but that isn't necessarily accurate so I'd suggest you modify the function so it takes a second parameter indicating the number of significant bits. Then after reversing the bits just shift them to the right.
Try using Integer.reverse(int x);
Let assume you have two points (a , b) in a two dimensional plane. Given the two points, what is the best way to find the maximum points on the line segment that are equidistant from each point closest to it with a minimal distant apart.
I use C#, but examples in any language would be helpful.
List<'points> FindAllPointsInLine(Point start, Point end, int minDistantApart)
{
// find all points
}
Interpreting the question as:
Between point start
And point end
What is the maximum number of points inbetween spaced evenly that are at least minDistanceApart
Then, that is fairly simply: the length between start and end divided by minDistanceApart, rounded down minus 1. (without the minus 1 you end up with the number of distances between the end points rather than the number of extra points inbetween)
Implementation:
List<Point> FindAllPoints(Point start, Point end, int minDistance)
{
double dx = end.x - start.x;
double dy = end.y - start.y;
int numPoints =
Math.Floor(Math.Sqrt(dx * dx + dy * dy) / (double) minDistance) - 1;
List<Point> result = new List<Point>;
double stepx = dx / numPoints;
double stepy = dy / numPoints;
double px = start.x + stepx;
double py = start.y + stepy;
for (int ix = 0; ix < numPoints; ix++)
{
result.Add(new Point(px, py));
px += stepx;
py += stepy;
}
return result;
}
If you want all the points, including the start and end point, then you'll have to adjust the for loop, and start 'px' and 'py' at 'start.x' and 'start.y' instead. Note that if accuracy of the end-points is vital you may want to perform a calculation of 'px' and 'py' directly based on the ratio 'ix / numPoints' instead.
I'm not sure if I understand your question, but are you trying to divide a line segment like this?
Before:
A +--------------------+ B
After:
A +--|--|--|--|--|--|--+ B
Where "two dashes" is your minimum distance? If so, then there'll be infinitely many sets of points that satisfy that, unless your minimum distance can exactly divide the length of the segment. However, one such set can be obtained as follows:
Find the vectorial parametric equation of the line
Find the total number of points (floor(length / minDistance) + 1)
Loop i from 0 to n, finding each point along the line (if your parametric equation takes a t from 0 to 1, t = ((float)i)/n)
[EDIT]
After seeing jerryjvl's reply, I think that the code you want is something like this: (doing this in Java-ish)
List<Point> FindAllPointsInLine(Point start, Point end, float distance)
{
float length = Math.hypot(start.x - end.x, start.y - end.y);
int n = (int)Math.floor(length / distance);
List<Point> result = new ArrayList<Point>(n);
for (int i=0; i<=n; i++) { // Note that I use <=, not <
float t = ((float)i)/n;
result.add(interpolate(start, end, t));
}
return result;
}
Point interpolate(Point a, Point b, float t)
{
float u = 1-t;
float x = a.x*u + b.x*t;
float y = a.y*u + b.y*t;
return new Point(x,y);
}
[Warning: code has not been tested]
Find the number of points that will fit on the line. Calculate the steps for X and Y coordinates and generate the points. Like so:
lineLength = sqrt(pow(end.X - start.X,2) + pow(end.Y - start.Y, 2))
numberOfPoints = floor(lineLength/minDistantApart)
stepX = (end.X - start.X)/numberOfPoints
stepY = (end.Y - start.Y)/numberOfPoints
for (i = 1; i < numberOfPoints; i++) {
yield Point(start.X + stepX*i, start.Y + stepY*i)
}