I am computing the distance of an object.
The X and Y position values first stored in two different Lists X and W.
Then I use another List for storing the distance covered by this object. Also, I refresh the lists if their count reaches 10, in order to avoid memory burden.
On the basis of distance value, I have to analyze, if the object is in the static position the distance should not increases. And on the text box display, the computed distance values appears to be static.
Actually, I am using sensors to compute the distance. And due to sensor error even if the object is in the static state the distance value varies. The sensor error threshold is about to be 15cm.
I have developed the logic, However, I receive error:
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'
My code is as follows:
void distance()
{
List<double> d = new List<double>();
double sum = 0, sum1 = 0;
for (int i = 1; i < X.Count; i++)
{
//distance computation
if ((d[i] - d[i -1]) > 0.15)
{
sum1 = d.Sum();
sum = sum1 + dis1;
Dis = Math.Round(sum, 3);
}
}
// refresh the Lists when X, W and d List reach the count of 10
}
}
You do it totally wrong. Come up with a method computing a distance for a two given points. That's gonna be a func of signature double -> double -> double or, if you prefer C#, double ComputeDistance(double startPoint, double endPoint).
Then the only thing to do is to apply such a fuction to each pair of points you got. The easiest and most compact way to accomplish that is by means of Linq. It could be done in a regular foreach as well.
Take a note that it would be a way clearer if you will eventually merge your separated lists into a single list. Tuple<double, double> seems to be the best choice including performance.
Related
Problem:
I know the x and y of three arbitrary points on a 2d plane.
I know the vague distance from each point to the unknown, though I don't know the x y components.
I want to find the position of the 4th point.
The data is stored in a list >3 of type Data where
public class Data
{
double m_x, m_y, m_distance;
}
I've tried:
Walking the list, calculating the components of the distance, then adding the known x and y. I then calculated the average position of the predicted point from the 3 known points, but the accuracy was inconsistent.
foreach (var item in data_list)
{
var dx = item.m_x + item.m_distance * Math.Cos(item.m_distance);
var dy = item.m_y + item.m_distance * Math.Sin(item.m_distance);
out_list.Add(new Data { m_x = dx, m_y = dy });
}
foreach (var item in out_list)
{
__dx += item.m_x;
__dy += item.m_y;
}
__dx /= return_list.Count;
__dy /= return_list.Count;
Creating three circles at the known x and y, extending their radii equal to the distance component and checking intersection. The problem is that the distance varies since its rather imprecise, more like a suggestion.
Is there a simple, ok-performing, witty solution to this problem that I can't grasp?
I've thought of extending lines 360 degrees around each point and checking where three lines intersect, the shortest distance away from the origin, but I'm not entirely sure about the implementation.
I have implemented a version of the AdaBoost boosting algorithm, where I use decision stumps as weak learners. However often I find that after training the AdaBoost algorithm, a series of weak learners is created, such that this series is recurring in the whole set. For example, after training, the set of weak learners looks like A,B,C,D,E,D,E,D,E,D,E,F,E,D,E,D,E etc.
I believe I am updating the weights of the data properly after each assignment of a new weak learner. Here I classify each data point and then set the weight of this data point.
// After we have chosen the weak learner which reduces the weighted sum error by the most, we need to update the weights of each data point.
double sumWeights = 0.0f; // This is our normalisation value so we can normalise the weights after we have finished updating them
foreach (DataPoint dataP in trainData) {
int y = dataP.getY(); // Where Y is the desired output
Object[] x = dataP.getX();
// Classify the data input using the weak learner. Then check to see if this classification is correct/incorrect and adjust the weights accordingly.
int classified = newLearner.classify(x);
dataP.updateWeight(y, finalLearners[algorithmIt].getAlpha(), classified);
sumWeights += dataP.getWeight();
}
Here is my classify method in the WeakLearner class
// Method in the WeakLearner class
public int classify(Object[] xs) {
if (xs[splitFeature].Equals(splitValue))
return 1;
else return -1;
}
Then I have a method which updates the weight of a DataPoint
public void updateWeight(int y, double alpha, int classified) {
weight = (weight * (Math.Pow(e, (-y * alpha * classified))));
}
And I'm not sure why this is happening, are there any common factors why the same weak learners would generally be chosen?
You could increase the value of alpha and check. Maybe, not enough weight is being given to the misclassified samples, hence ,they are showing up again and again.
I have a function to return the total length of a NavMesh path, using Vector3.SqrMagnitude to avoid the overhead of the Sqrt calculation in Vector3.Distance:
float DistanceAlongPath(NavMeshPath path)
{
float sum = 0;
for (int x = 0; x < path.corners.Length - 1; x++)
{
sum += Vector3.SqrMagnitude(path.corners[x + 1] - path.corners[x]);
}
return sum;
}
When the path only has two points the calculation seems fine, however at 3 points or more it always returns a smaller value for a long line than it does for a short line of only 2 points.
The distance shown in the first image is 3848, in the second it's 3419 despite being a much longer path.
Vector3.Distance works correctly with any number of points.
Am I missing something?
SqrMagnitude gives only an approximation of length. While values of SqrMagnitude can be compared to each other for relative length comparison, they do not give a true length, so you can't just combine them.
The root of your problem here is in the math, specifically in the order in which addition and multiplication are handled:
(5+5+5)^2 != (5^2 + 5^2 + 5^2)
For example, if you have 3 line segments, each of length 5, each will have SqrMagnitude of 25. Add them and you get 115.
Now consider a single line segment with length 15. SqrMagnitude is 225.
In either case, if you apply the square root operation to get a true length, you get the same result. 3*Sqrt(25) == 1*Sqrt(225)
In the homework I am doing:
It is stated: "You may NOT use a number to access a tile - if you are using a number to find a tile, then it is most likely your design is not object oriented."
So essentially, my question is this:
If one were to not use an index to get an object from a list of objects, would the only solution be to use a foreach loop, every time you needed to retrieve a specific object?
If not, could you please provide an example (e.x. using a "for loop in an object oriented way", or other solutions instead of using an index)?
My concern is the amount of bloat (in lines) that might be created when not using for loops - and the affect that might have on speed.
e.g., I have the following:
for (int i = dimensions-1; i >= 0; i--)
{
map += "-";
for (int j = 0; j < dimensions; j++)
{
//For 4X4Y is 24. 3X4Y is 19. and so on.
//For 4X3Y is 23. 3X3Y is 18. and so on.
//As you can see: j * dimensions represents a "generalized" x value. adding it by i, represents its y value.
Tile currentTile = _game.TileSet[(j * dimensions) + i];
if (currentTile.Visitor == null)
map += "X-"; //X implies no robot
else
map += "R-"; //R implies robot
}
}
Yes this code is kind of ugly, but my list is formatted in such a way that I can't just use one foreach loop, and split the line on each x amount of tiles per line, as the list is stored vertically, and then horizontally, as opposed to horizontally, and then vertically (which would allow a simple foreach to suffice).
My concern is that if this is "not object oriented" - then using a foreach loop, would require a LOT more iterations.
Anyway, if anyone has an answer to the question I would really appreciate your thoughts.
Thanks.
Edit: Instead of using X and Y values, in a 2D List/Array, the list is 1d, and we are required to use association by having a list of connecting tiles, 4 elements, each element representing a typical compass direction in which the adjacent tile is located. There are no properties - however there is one method which can return an adjacent tile at a specified direction GetTileAtDirection(Direction).
The tileSet is a list of 25 elements, with 0 through 4 being the first 5 elements, X = 0, Y = 0 X = 0, Y = 1 X = 0, Y = 2 X = 0, Y = 3 X = 0, Y = 4. For the next five elements, X is incremented by one, representing the next five values in this "Y line"...
Note that there are no X and Y variables in which each tile can be accessed. This is a requirement in the homework.
If one were to not use an index to get an object from a list of
objects, would the only solution be to use a foreach loop, every time
you needed to retrieve a specific object?
No. I think the idea is that each tile should have a mapping of Direction to Tile, and GetTileAtDirection simply looks it up. The code that creates the tiles would need to assign the relationships, something like this:
nextTile = new Tile();
nextTile.AdjacentTiles[Direction.Left] = previousTile;
previousTile.AdjacentTiles[Direction.Right] = nextTile;
and so on. Of course, this code would probably be looking up the indices in TileSet, but the key is that an individual tile object can be completely independent from it -- the Tile class wouldn't even need a reference to a Game object or TileSet.
I'm not really good in maths, so I'm having really hard times converting formulas into code, and I can't find anything ready-made googling around. I have a big rectangle containing a lot of small rectangles... and all what I need to do is to calculate the largest empty rectangle. Anyonne can help me?
Here is what I came up with... nothing to say, it's a big fail.
Rect result = new Rect();
for (Double l = 0; l < bigRect.Width; ++l)
{
for (Double t = 0; t < bigRect.Height; ++t)
{
Double h = 0;
Double w = 0;
while ((h <= bigRect.Width) && (w <= bigRect.Height))
{
Rect largestEmpty = new Rect(l, t, w, h);
if (smallRects.TrueForAll(smallRect => !smallRect.IntersectsWith(largestEmpty)) && ((largestEmpty.Height * largestEmpty.Width) > (result.Height * result.Width)))
result = largestEmpty;
else
break;
++h;
++w;
}
}
}
From your Perdue Docs Link it says there is a set (let's call it ASD) of points in the Big Rect and you would to have find the largest Rect containing no points of the set ASD. Looking at your code, it seems you didn't (directly) incorporate these points. I would extract the points from the smaller Rects ans create set ASD. Since your working in type double, you should have access to the points, otherwise the algorithm would have a significantly higher run time since you need to check all possible doubles in a specific range (the entire Big Rect). Using the points, I would trying find the points with the shortest distance form each other (sqrt(dx^2+ dy^2)) (shortest shouldn't contain any points) then go to the next shortest and see if any points are contained and etc. In other words, create a order list of all combinations (not permutations, (a,b) to (c, d) should be == (c, d) to (a,b)) ordered by the distance in between them. Might not be optimal, but gets the job done.
EDIT: All order pair besides the diagonals of the smaller Rects should be in the order list, since the smaller Rects should not be conatined, You can also exclude pairs with the same x or y value.