Imaginary number comparison with C# [duplicate] - c#

This question already has answers here:
Rule of thumb to test the equality of two doubles in C#?
(6 answers)
Closed 11 months ago.
I want to analyse a polynomial and only output the real roots. I use the Systems.Numerics to get the complex number and then compare their imaginary component to a set value to find out if they are real. To analyse the polynom, I use MathNet.Numerics for the analysis. The outputs should later be processed and printed out, but for testing reasons, I also print out the full complex number.
This is my code:
Complex[] roots = func.Roots();
List<double> realroots = new List<double>();
// Complex[] rootsDis = roots.Distinct().ToArray();
foreach (var root in roots)
{
if (root.Imaginary == 0)
{
string Root = root.Real.ToString();
double.TryParse(Root, out double RealRoot);
realroots.Add(RealRoot);
Ausgabe.Items.Add(root.ToString());
}
else
{
Ausgabe.Items.Add("no real roots");
return;
}
}
My problem is, that even if the imaginary component is 0 when printed out, the if statement is not fulfilled an also inserting conditions like >0,001 does not help either (I did the same in python once and
used numpy, there it helped). What can I do to correct that?
Edit: I solved it by deleting the return in the else statement. What i didnt grasp was, that a foreach loop goes through the array one by one and my programm failed becaus it broke the loop when it found the first non real root. But, thanks for your help nonetheless, I learend some things from it.

Could you compare with some calibrated epsilon?
For example:
if (Math.Abs(root.Imaginary) < 0.0000001)
{
// This is real!
}

Related

Pick the lowest element in a list [duplicate]

This question already has answers here:
C# Finding the maximum value of a string with linq
(3 answers)
Closed 4 years ago.
I want to choose the media based on the size, but can't seem to figure out how to pick the one with lowest memory consumption in a smart way.
The memory usage is stored in the field Size.
using System;
using System.Collections.Generic;
struct placeholder
{
string size;
public placeholder(string input)
{
this.size = input;
}
}
public class Program
{
public static void Main()
{
List<placeholder> list = new List<placeholder>();
list.Add(new placeholder("1"));
list.Add(new placeholder("2"));
list.Add(new placeholder("3"));
list.Add(new placeholder("4"));
// How to find the entry in list with lowest placeholder.size?
Console.WriteLine("Hello World");
}
}
But how do I pick the one with with the lowest memory, the size is stored as a string?
I could do it a for loop, but is there something smarter?
There is nothing smarter than going through the list. Period.
It is a LIST - it has no inner magic knowledge about a special condition, so to find one matching a specific condition (lowest memory) you must go through all the elements and evaluate them. Period - intrinsic basic logic, nothing smart is possible here.
Take every element, compare the size to the size stored for the size of the smallest element and replace the smallest element if it is smaller (and define what to do on same size).
You cannot avoid "visiting" each element of the entire list regardless of the solution you go with because in order to get the min item you're required to compare against every other item.
You can get the result via Linq Aggregate :
var min = list.Aggregate((l, r) => int.Parse(l.size) > int.Parse(r.size) ? r : l);
or use a typical for loop.
Typical solution for this problem is sorting the list then taking the first or last item depending on your sort algorithm.

How to get random number with each number has its own probability [duplicate]

This question already has answers here:
how to implement non uniform probability distribution?
(3 answers)
Closed 9 years ago.
For example, I want to get random number from set S = {0, 1, 2, 3}. But instead of each number has same probability to shown (which is 25%), now I have different probability for each number, let say {50%, 30%, 20%, 10%}.
How do I code this? In Java or C# (I prefer C#).
The Alias Method is by far my favorite for doing this.
http://code.activestate.com/recipes/576564-walkers-alias-method-for-random-objects-with-diffe/
I haven't reviewed this code but it is a top google result.
Here is another much better explanation
http://pandasthumb.org/archives/2012/08/lab-notes-the-a.html
I actually use this question for interviews quite often since if you have never seen it before it can be pretty puzzling.
If the above is too much for you to implement there is a simpler one loop through the input solution.
Using PHP since it is easier to just show the code.
function getNumberFromDistribution($dist) {
$totalProbability = 0;
$randomNumber = mt_rand(0, mt_getrandmax()) / mt_getrandmax(); //uniform random number between 0-1
foreach($dist as $number => $chance) {
if (($totalProbability += $chance) <= $randomNumber) {
return $number;
}
}
return null; //only reachable on bad input
}
If the set is small you can build an array that contains the right number of each value you need to get your distribution eg. 1 1 1 2 2 3 would provide 3 times the likelihood of getting a 1 as it does of getting a 3. You would then use the length of the array to determine the random number that you use as an index.

Basic Guessing Game Mechanics in C#

I've had quite a bit of experience with programming (three semesters teaching VBasic, C++, and Java), and now I'm in college and I'm taking a C# class, which is quite boring (the teacher knows less than I do).
Anyways, for one of our exercises, we're creating a number guessing/lottery game. It works kind of like this:
User inputs three integers from 1-4 and clicks submit (I have them storing into an array)
Program generates three numbers from 1-4 (also in an array)
Function that checks matching runs and checks the two arrays
If all three match in order (i.e. 1,2,3 = 1,2,3 and NOT 1,2,3 = 1,3,2), matching = 4
If all three match NOT in order, matching = 3
If only two match, matching = 2
I want to make sure that only one match counts as one (i.e. [1,1,2][1,2,3] only gives one match to the user.
If only one matches, matching = 1
If no matches, matching stays at 0 (it's instantiated at submit_click)
I've got all of the code and GUI working except for the matching logic. I know I could do it with a LARGE amount of if statements, and I know cases would probably work, but I'm not as experienced with cases.
I'm not expecting my 'homework' to be done here, but I just want to know what method would be most effective to get this to correctly work (if it's easier to exclude the one match per item, then that's fine), and to possibly see some working code.
Thanks!
EDIT
I apologize if I come across as arrogant, I didn't mean to come across as a know-it-all (I definitely do not).
I have NOT taught classes, I've just taken classes from a teacher who's primarily a programming in and I'm at a community college and my professor isn't primarily a programming teacher.
I didn't take time to write a ton of if statements because I know that it would just get shot down as ineffective. I currently don't have the resources to test the answers, but as soon as I can I'll check them out and post back.
Again, I apologize for coming across as rude and arrogant, and I appreciate your answers more than you know.
Thanks again!
You can use a loop to achieve this functionality. I've used a list simply for ease of use, performing remove operations and the like. Something like this should work:
public static int getNumberOfMatches(List<int> userGuesses, List<int> machineGuesses) {
// Determine list equality.
bool matchedAll = true;
for (int i = 0; i < userGuesses.Count; i++) {
if (userGuesses[i] != machineGuesses[i]) {
matchedAll = false;
break;
}
}
// The lists were equal; return numberOfGuesses + 1 [which equals 4 in this case].
if (matchedAll) {
return userGuesses.Count + 1;
}
// Remove all matches from machineGuesses.
foreach (int userGuess in userGuesses) {
if (machineGuesses.Contains(userGuess)) {
machineGuesses.Remove(userGuess);
}
}
// Determine number of matches made.
return userGuesses.Count - machineGuesses.Count;
}
I think for the first case, for all matches in order you would scan the arrays together and maybe increment a counter. Since you mentioned you know c++, this would be
int userGuesses[3];
int randomGen[3];
int matches = 0;
for(int i=0; i < 3; i++) if(userGuesses[i] == randoGen[i]) matches++;
if(matches == 3) //set highest score here.
if(matches == 2) // next score for ordered matches etc.
For the not-in-order case, you will need to lookup the generated array for each user guess to see if it has that value.

C#: for verses foreach [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
For vs Foreach loop in C#
Is one better than another?
Seems I've heard that a for loop has less overhead than a foreach, but I've yet to see the proof of this.
One being "better" than the other depends on your application. Are you just reading a data structure? Are you writing to a data structure? Are you not even using any sort of data structure and just doing some math?
They each have their own uses. The for each loop is usually used for reading things from a data structure (array, linked list etc). For example.
foreach(myClass i in myList)
{
int x = i.getX();
console.writeline(x);
}
Where the for loop can be used to do the above, among other things such as update a data structure entry.
for (int i = 0; i < myList.count(); i++)
{
myList[i].x += i * 80;
}
Use foreach if you don't need the index (which is most of the time in most applications) otherwise use for.
The compiler of today has gotten a lot better than the compiler of .net 1.
While for is more optimized, foreach over an array is actually translated in the IL to a for.
Foreach over a generic collection is optimized in that it returns a generic ienumerator and linq has some neato optimizations around that as well.
So the short answer is yes, but the real world answer is no.

C# Find the Next X and Previous Numbers in a sequence

I have a list of numbers, {1,2,3,4,...,End} where End is specified. I want to display the X closest numbers around a given number Find within the list. If x is odd I want the extra digit to go on the greater than side.
Example (Base Case)
End: 6
X: 2
Find: 3
The result should be: {2,3,4}
Another Example (Bound Case):
End: 6
X: 4
Find: 5
The result should be: {2,3,4,5,6}
Yet Another Example (Odd Case):
End: 6
X: 3
Find: 3
The result should be: {2,3,4,5}
I'm assuming it would be easier to simply find a start and stop value, rather than actually generating the list, but I don't really care one way or another.
I'm using C# 4.0 if that matters.
Edit: I can think of a way to do it, but it involves way too many if, else if cases.
if (Find == 1)
{
Start = Find;
Stop = (Find + X < End ? Find + X : End);
}
else if (Find == 2)
{
if (X == 1)
{
Start = Find;
End = (Find + 1 < End ? Find + 1 : End);
}
...
}
You can hopefully see where this is going. I assuming I'm going to have to use a (X % 2 == 0) for odd/even checking. Then some bound thats like less = Find - X/2 and more = Find + X/2. I just can't figure out the path of least if cases.
Edit II: I should also clarify that I don't actually create a list of {1,2,3,4...End}, but maybe I need to just start at Find-X/2.
I realise that you are learning, and out of respect from this I will not provide you with the full solution. I will however do my best to nudge you in the right direction.
From looking at your attempted solution, I think you need to figure out the algorithm you need before trying to code up something that may or may not solve your problem. As you say yourself, writing one if statement for every possible permutation on the input is not a manageble solution. You need to find an algorithm that is general enough that you can use it for any input you get, and still get the right results out.
Basically, there are two questions you need to answer before you'll be able to code up a working solution.
How do I find the lower bound of the list I want to return?
How do I find the upper bound of the list I want to return?
Considering the example base case, you know that the given parameter X contains a number that tells you how many numbers around Find you should display. Therefore you need to divide X equally on both sides of Find.
Thus:
If I get an input X = 4 and Find = 3, the lower bound will be 3 - 4/2 or Find - X/2.
The higher bound will be 3 + 4/2 or Find + X/2.
Start by writing a program that runs and works for the base case. Once that is done, sit down and figure out how you would find the higher and lower bounds for a more complicated case.
Good luck!
You can look at Extension methods. skip and take.
x.Skip(3).Take(4);
this will help u in what u r trying to do

Categories