Calling a boolean method inside the where clause of a Linq query - c#

I've a query in Linq that calls a method inside the where clause...
Here's the code:
it = {my iter}
{
...
return from l in lifts
where(compare(l.Trip.Start, it.Start, startRadius))
select l;
}
private bool compare(POI a, POI b, int radius)
{
return (((b.Position.X.Value - radius < a.Position.X.Value)
&& (a.Position.X.Value < b.Position.X.Value + radius))
&& ((b.Position.Y.Value - radius < a.Position.Y.Value)
&& (a.Position.Y.Value< b.Position.Y.Value + radius)));
}
but the query returns every time all the lifts list. Why the method compare returns every time true?
Where I'm wrong?
Thank you

There has to be something wrong with your data or compare method.
There is nothing magical in how where works. I bet that if you place return false in compare method, returned list will be empty.
Update: you should consider #Jacob Proffitt answer too if you aren't sure of it.Start value at the time of query execution (I don't know why it is down-voted).
Try to replace LINQ query with simple foreach loop and step through code with debugger.
As suggested in comments, in compare method you probably want to measure if two points are within some range. So:
double x1 = a.Position.X.Value;
double y1 = a.Position.Y.Value;
double x2 = b.Position.X.Value;
double y2 = b.Position.Y.Value;
return ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) < (r*r);

Related

Heron Algorithm Recursive C#

I'm trying to implement the heron algorithm recursively in C#.
I don't really understand where my code is wrong:
Given definition of algorithm:
x[n+1] = (p-1) /p*x[n] + a/p*x[n]^p-1
Where xo = 1 and p root a
public static double Heron(int x,int p,int a)
{
if(x == 0)
{
return 1.0;
}
return ((p-1.0)/p)*Heron(--x,p,a)+a/(p*Math.Pow(Heron(--x,p,a),--p));
}
e.g Heron(1,3,5) should return 7/3;
Don't modify the value of x and p in your expression.
Just use
double x_n = Heron(x-1,p,a);
return ((p-1.0)/p)*x_n+a/(p*Math.Pow(x_n,p-1));
I have also kept the value of the recursion in x_n so it does not get called twice.

C# - Stuck with use of list and array

I have been practicing c# nowadays and decided to write a code that converts any decimal to any base representation for practice purpose. And i have some troubles. Since i want to practice i decided to do it with an additional function where calculations take place. First i wanted to use an array to keep my result. But since ,at the beginning, i do not know the length of the array i could not define it.So i decided to use list(somehow i assumed undeclared slots are 0 as default). This is what i end up with.
class MainClass
{
static double number;
static double baseToConvert;
static int counter = 0;
static List<double> converted = new List<double>();
public static void Main(string[] args)
{
Console.WriteLine("Enter a decimal");
number = double.Parse(Console.ReadLine());
Console.WriteLine("Enter a base you want to convert to");
baseToConvert = double.Parse(Console.ReadLine());
ConverterToBase(number);
for (int i = converted.Count - 1; i >= 0; i--)
{
Console.WriteLine(converted[i]);
}
Console.ReadLine();
}
public static void ConverterToBase(double x)
{
double temp = x;
while (x >= baseToConvert)
{
x /= baseToConvert;
counter++;
}
converted[counter] = x;
counter = 0;
if (temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)) >= baseToConvert)
{
ConverterToBase(temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)));
}
else
{
converted[0] = temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter));
}
}
}
But after i write inputs console gets stuck without an error. My guess is that since i do not have any elements in the list " converted[counter] " does not make sense. But i do not know maybe the problem is somewhere else.
My question is not about the way i calculate the problem(Of course any suggestions are welcomed). I just want to know what i am doing wrong and how i can handle such situation(unknown array size , use of list , accessing a variable,array,.. etc from another method... ).
Thanks.
My previous answer was wrong as pointed out by #Rufus L. There is no infinite for loop. However upon further review, there seems to be an infinite recursion going on in your code in this line:
if (temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)) >= baseToConvert)
{
ConverterToBase(temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)));
}
ConverterToBase calls itself and there seems to be no base case nor return statement to end the recursion.
In the method named "ConverterToBase(double x)" you want to set value of 0 element. But you didn't add any element. The converted is Empty.
Firstly add value or values to your list.

double delay code for single variable two condition

in my project, i need to code for X1 in such a way as
in local variables i declare and wrote the condition as
x1 = 0;
if(in1_w == 1)
{
x1 = 1;
}
if((in1_w == 1) && (in2_w == 1))
{
x1 = 2;
}
i's an microcontroller based in and out so, now i need to know how to right the delay code if x1=1 and x1=2. i have written as
for(k=0;k<=x1;k++)
{
delay_40sec();
}
but don't know how to write separately?
waiting for your kind help plz
You can use
System.Threading.Thread.Sleep(x)
where x is in milliseconds.
However be aware that it is not guaranteed to be accurate nor repeatable.

What wrong with this implement of this arcsine approximate in C#

This is a formula to approximate arcsine(x) using Taylor series from this blog
This is my implementation in C#, I don't know where is the wrong place, the code give wrong result when running:
When i = 0, the division will be 1/x. So I assign temp = 1/x at startup. For each iteration, I change "temp" after "i".
I use a continual loop until the two next value is very "near" together. When the delta of two next number is very small, I will return the value.
My test case:
Input is x =1, so excected arcsin(X) will be arcsin (1) = PI/2 = 1.57079633 rad.
class Arc{
static double abs(double x)
{
return x >= 0 ? x : -x;
}
static double pow(double mu, long n)
{
double kq = mu;
for(long i = 2; i<= n; i++)
{
kq *= mu;
}
return kq;
}
static long fact(long n)
{
long gt = 1;
for (long i = 2; i <= n; i++) {
gt *= i;
}
return gt;
}
#region arcsin
static double arcsinX(double x) {
int i = 0;
double temp = 0;
while (true)
{
//i++;
var iFactSquare = fact(i) * fact(i);
var tempNew = (double)fact(2 * i) / (pow(4, i) * iFactSquare * (2*i+1)) * pow(x, 2 * i + 1) ;
if (abs(tempNew - temp) < 0.00000001)
{
return tempNew;
}
temp = tempNew;
i++;
}
}
public static void Main(){
Console.WriteLine(arcsin());
Console.ReadLine();
}
}
In many series evaluations, it is often convenient to use the quotient between terms to update the term. The quotient here is
(2n)!*x^(2n+1) 4^(n-1)*((n-1)!)^2*(2n-1)
a[n]/a[n-1] = ------------------- * --------------------- -------
(4^n*(n!)^2*(2n+1)) (2n-2)!*x^(2n-1)
=(2n(2n-1)²x²)/(4n²(2n+1))
= ((2n-1)²x²)/(2n(2n+1))
Thus a loop to compute the series value is
sum = 1;
term = 1;
n=1;
while(1 != 1+term) {
term *= (n-0.5)*(n-0.5)*x*x/(n*(n+0.5));
sum += term;
n += 1;
}
return x*sum;
The convergence is only guaranteed for abs(x)<1, for the evaluation at x=1 you have to employ angle halving, which in general is a good idea to speed up convergence.
You are saving two different temp values (temp and tempNew) to check whether or not continuing computation is irrelevant. This is good, except that you are not saving the sum of these two values.
This is a summation. You need to add every new calculated value to the total. You are only keeping track of the most recently calculated value. You can only ever return the last calculated value of the series. So you will always get an extremely small number as your result. Turn this into a summation and the problem should go away.
NOTE: I've made this a community wiki answer because I was hardly the first person to think of this (just the first to put it down in a comment). If you feel that more needs to be added to make the answer complete, just edit it in!
The general suspicion is that this is down to Integer Overflow, namely one of your values (probably the return of fact() or iFactSquare()) is getting too big for the type you have chosen. It's going to negative because you are using signed types — when it gets to too large a positive number, it loops back into the negative.
Try tracking how large n gets during your calculation, and figure out how big a number it would give you if you ran that number through your fact, pow and iFactSquare functions. If it's bigger than the Maximum long value in 64-bit like we think (assuming you're using 64-bit, it'll be a lot smaller for 32-bit), then try using a double instead.

Arraylist of points

I have a program that find coordinates between two point with a predefined interval:
ArrayList<Point> genPoints(double smallDist, Point a, Point b)
{
ArrayList<Point> outputPoints = new ArrayList<Point>();
double distAB = dist2Points(a, b);
if (smallDist > distAB)
return null;
int numGeneratedPoints = (int)(distAB / smallDist);
Vector vectorBA = b - a;
vectorBA.Normalize();
Point currPoint = a;
for (int i = 0; i < numGeneratedPoints; i++)
{
currPoint = currPoint + vectorBA * smallDist;
if (dist2Points(currPoint, b) != 0)
outputPoints.Add(currPoint);
}
return outputPoints;
}
now I called that method using the following code, where I am passing two points P1, P2 and predefined distance.
gp = genPoints(1, p1, p2)
when I want to show the values, it gives me the following:
4.94974746830583,4.94974746830583
5.65685424949238,5.65685424949238
6.36396103067893,6.36396103067893
7.07106781186548,7.07106781186548
7.77817459305202,7.77817459305202
for (int i = 0; i < gp.Count; i++)
System.Console.WriteLine(" " + gp[i]);
I don't know how to access those values individually. I couldn't even use gp[i].x or gp[i].y. but, somehow I need to access those values separately.
Any help would be greatly appreciated.
The problem is that you're using a non-generic collection, ArrayList. The indexer is just returning object, so you have to cast:
Point p = (Point) gp[i];
// Now you can use p.x etc
If you're using .NET 2 or higher, it would be better to use a generic collection such as List<T> - make your method return a List<Point> and you'll be able to write:
Point p = gp[i];
... no cast is required.
There are a number of benefits to generics - unless you're forced to use non-generic collections (e.g. you're writing code for .NET 1.1) you should pretty much avoid them and always use the generic collections.
As an aside, methods conventionally start with a capital letter in .NET - so I would name this method GeneratePoints instead.

Categories

Resources