i have an R script that make some calculations.
and i found the same script but in C# , but it's giving me answers different than R.
the R code is :
count=16569
for(ind1 in seq(1,count,by=1000))
{
for(ind2 in seq(1,count,by=1000))
{
value=(count*(ind1^2)) + ((count*(count+1)*((2*count)+1))/6) -(2*ind1*((count*(count+1))/2)) + (2*count*ind1*(count-ind2+1)) + ((count-ind2+1)*(count^2)) + (2*count*(ind2-count-1)*(ind2+count))
}
}
and the C# code is :
double count=16569
for(int ind1=1;ind1<=count;ind1+=1000)
{
for(int ind2=1;ind2<=count;ind2+=1000)
{
value=(count*(Math.Pow(ind1,2))) + ((count*(count+1)*((2*count)+1))/6) -(2*ind1*((count*(count+1))/2)) + (2*count*ind1*(count-ind2+1)) + ((count-ind2+1)*(Math.Pow(count,2))) + (2*count*(ind2-count-1)*(ind2+count))
}
}
for the first round , the value in R is : -3032615095125
but the value in C# is : 4548002182315
what is the error ?
thanks
Looking at your code, I see that the loops won't make any difference. The values from the previous iteration of your loop are never stored or accessed, so value will always be set by the last run of the loop.
In effect, you just have three constants: count = 16569 ind1 = 16001 ind2 = 16001
And the answer is 1.209314e+12, whether or not the loops are run.
In C# (once I add semicolons and a variable declaration for value so it will run):
1209314008875
So I get the same answer in both R and C#. I know you asked why the answers are different, but you might look at whether the code is doing what you want in the first place; I'm not sure why the loops are there. With the code you've given, you could just plug-in the constants above to verify what your machine is giving you.
I don't know R, but with respect to C#, What datatype is the variable value? Could it be that the values are overflowing and therefore junk?
Check the bit sizes of your variables. The value in R looks fishy.
Also, why is count double and not int?
Related
I was reading through some code on Github recently and i came across the following line,
if (((tmp = rx.IndexOf("<")) >= 0) && (rx.IndexOf(">") > tmp ))
specifically the
(tmp = rx.IndexOf("<") >= 0)
And the immediate use of the tmp variable in a comparison in the same line in the next part of the if statement
(rx.IndexOf(">") > tmp )
in which a variable is being set by a string,indexOf() method, and then the 'assignment statement itself' is being evaluated with a greater-or-equal-to equality operator.
At first i thought this was a typo, but on evaluating the code via a simple console app, i found it to be valid, and a great shortcut.
The question is "What is the technical term for this?" as i could find no explanation in various C# help sites.
An example console app to demonstrate how the statement was used.
public static void Main()
{
// first test - the actual code I found in gitHub
int tmp;
int tmp2;
string rx = " < test>";
// the below line is the subject of the question.
if (((tmp = rx.IndexOf("<")) >= 0) && (rx.IndexOf(">") > tmp )){
Console.WriteLine("The Close brace is after the opening brace!");
}
// additional test
int r;
Console.WriteLine(r = 25 + 3);
Console.WriteLine(r);
// and another
int w = -1;
Console.WriteLine(" The index of '<' is greater than 0 : " + _
((w = rx.IndexOf("<")) > 0).ToString() + _
" and the value of w is " + w.ToString());
}
The output of the above code is below.
Again , I understand the code works, I would like to know what is this called technically?
The Close brace is after the opening brace!
28
28
The index of '<' is greater than 0 : True and the value of w is 2
There is no "technical term".
It's an assignment, and a assignment can act as expression or a statement.
It's a statement that has a value; Or an Expression where the result value can be ignored. (Unlike x+y, the Result is not allowed to be ignored)
It's the same as the prefix and postfix operators i++;
It will look less like "inline" in a line like x = y = z;
However, it's not often used, cause it's less readable, as you just proofed.
And in your case, assigning a value and using the value in the same expression tree
highly depends on evaluation order, which is well defined, but who knows it by heart ?
This style of writing will safe you a line of code (by making one line longer)
but it will never save you any operation, hence not cause any performance.
So Read it, Understand it, but better don't use it frequent.
This is just a consequence of assignment being an expression. It is defined in the C# specification:
7.17.1 Simple Assignment
The = operator is called the simple assignment operator.
The result of a simple assignment expression is the value assigned to
the left operand. The result has the same type as the left operand and
is always classified as a value.
So the value of
tmp = rx.IndexOf("<")
is the value assigned to tmp which is rx.IndexOf("<"). This value is then compared to 0 in the outer expression.
I would like to assign a value if P true then run a while loop with P.
This is the obvious solution:
int thevalue = 0;
// Calculate P
if(P)
{
theValue = 2;
}
while(P)
{
// Do something without modifying theValue and calculate P
}
But this looks nicer to me:
int theValue = 0;
// Calculate P
while(P)
{
theValue = 2;
// Do something without modifying theValue and calculate P
}
Will it assign every time the loop runs? Compiler could optimize this.
Is it a good practice?
EDIT:
The value is used after the loop.
The value should not change if P false when it examined.
More clear question:
If the while loop runs like a "billion times" is the assign in the loop ineffective and an unnecessary CPU cycle?
Functionally it is equivalent, but I'll address the 'good practice'...
P is clearly not invariant since otherwise your while loop would never terminate! If it's not invariant then the starting/initial condition you use in your 'if' statement must be different from the evaluation for each iteration of the loop.
I think what you are really trying to say with the 'if' statement is "set the value if the while loop will be evaluated at least once". As a matter of style I would write the code to make this intent clearer. If you can use a collection then I would suggest a pattern such as....
var theValue = collection.Any() ? 2 : someSensibleDefault;
foreach (var thing in collection)
{
}
If it truly is a test condition...
var theValue = (initialP) ? 2 : someSensibleDefault;
while (P)
{
}
As a final comment, I really wouldn't consider worrying about optimisation here - the goal should be to express what you trying to do.
The headline doesn't really fit but I'm not good at explaining in just one headline. Here goes: I want to put a double variable that changes depending on userinput into a Sortedlist and then loop through it so that it the output would be something like this:
Distance: 1
Distance : 2
Distance : 3
I can't use an arraylist because I don't know how many double values I will get.
I'm not really sure what you are asking for, so a wrote a code that will be "useful" for two scenarios: First, you want to access the last value that the user wrote. Second, you want to access all values on the list. And third, you want all of that on a single variable.
public class DistanceList : List<double>
{
public override string ToString()
{
int count = 1;
string resultString = String.Empty;
foreach (var item in this)
{
resultString = String.Concat(resultString, "Distance ", count.ToString(), ": ", item.ToString(), ";");
count = +1;
}
return resultString;
}
public static implicit operator double(DistanceList list)
{
return list.Single();
}
}
This class overrides the ToString method, and loops through all the values and add them on a string, giving the output you stated on your question "the output would be something like this: Distance: 1 Distance : 2 Distance : 3".
If you want the last value there is a implicit conversion for double which return the only value for the list, for one value will work just like a regular variable, for more than one value if you try to use as a double it will just trow an exception.
Just be aware that you will not be able to write directly to this variable and expect to add the item on the list, you will still need to use the List<T>().Add method.
But I really hope that it is not what you are asking for, because this kind of design will cause you a lot of trouble down the road.
Will you always be checking whether there is just one item so you can treat it as a double, or need to deal with many values? You will probably forget doing so somewhere...
This class only transforms them on a string, what if you need them as doubles to sum them up or something? You might end up parsing that string back into a List<double>...
I have an array of textboxes in which they change dyanmically depending on what the user types in. Those textboxes contain a number which represents a score of an assignment. Those score are linked to a module object. So if the user has 3 modules; 2 assignments on the first and second module and 3 assignments on the third module; then in total there would be 7 textboxes created for the user to input all their assignment marks.
What I am trying to do is to create a keyup event handler in which it gets the number in typed in by the user, and then dynamically calls a method to display the average of the the module. This is what I have so far. The following method gets called whenever the user types in a character:
public void calculateLevel4Modules(int counter) {
//iterate through modules
//iterate through assignts in that module
//whilst iterating, check tb and set userscore
//after iterating, update overall label with regards to modulecounter
//int assignmentCounter = 0;
//Console.WriteLine("in If statement.. " + counter);
for (int moduleCounter = 0; moduleCounter < requiredLevelList().Count; moduleCounter++)
{
int totalNumberOfAssignmentsInCurrentModule = requiredLevelList().ElementAt(moduleCounter).Assignments.Count;
Console.WriteLine("total number of assignmetns: " + totalNumberOfAssignmentsInCurrentModule);
assignmentCounter = assignmentCounter + totalNumberOfAssignmentsInCurrentModule;
Console.WriteLine("assignment counter: " + totalNumberOfAssignmentsInCurrentModule);
if (counter < assignmentCounter)
{
Console.WriteLine("in If statement.. " + userMarksTBLvl4[moduleCounter].Text);
try
{
int userMark = int.Parse(userMarksTBLvl4[counter].Text);
requiredLevelList().ElementAt(moduleCounter).Assignments.ElementAt(counter).UsersScore = userMark;
double modAvg = requiredLevelList().ElementAt(moduleCounter).getModuleScoreOverall();
moduleOverallLvl4[moduleCounter].Text = modAvg.ToString();
break;
}
catch (FormatException) { break; }
}
else { }
}
it works fine if the user has one module but if the user has two or more, then I get an error in the following line:
requiredLevelList().ElementAt(moduleCounter).Assignments.ElementAt(counter).UsersScore = userMark;
I am getting an out of bounds exception. I know why; its because counter is basically the # of the textbox that was typed into but by me using counter, I am accessing something not within the assignments list. This is an example of when the problem occus:
The user has 2 modules. In each module there are 2 assignments thus 4 textboxes are been created with their index ranging from 0 - 3. If the user wants to type in their score of the first assignment on the second module, its basically trying to write to the third index in that element then it crashes since that module only consist of 2 assignments.
There are some strange things in your code that make it hard to answer. First, the code you posted doesn't compile, so we have no way to test it.
Several times you use code like:
requiredLevelList().ElementAt(moduleCounter)
I assume requiredLevelList is a method that returns a list of things. There is no reason to assume requiredLevelList returns the same list, or even lists with the same number of elements, each time you call it. Maybe it does in your particular case, but this is a dangerous thing to rely on. You should use a construct like:
foreach (var module in requiredLevelList())
{
int totalNumberOfAssignmentsInCurrentModule = module.Assignments.Count;
...
module.Assignments.ElementAt(counter).UsersScore = userMark;
...
}
Code like this:
Console.WriteLine("total number of assignmetns: " + totalNumberOfAssignmentsInCurrentModule);
is symptomatic of trying to debug something after it has crashed. That is extremely inefficient. Learn how to use a debugger; you will not become an effective programmer until you know how to do this.
requiredLevelList().ElementAt(moduleCounter).Assignments.ElementAt(counter).UsersScore = userMark;
You're probably getting an out-of-bounds exception here because counter is outside the indexes of Assignments. Since you never initialize or change counter, I have no way to know what it is or should be. A debugger will tell you this, use one.
the # of the textbox that was typed into but by me using counter, I am accessing something not within the assignments list.
OK, if you're typing something “not within the assignments list” then you have to test for that and decide what to do. Perhaps something like:
if (counter >= 0 && counter < module.Assignments.Count)
module.Assignments.ElementAt(counter).UsersScore = userMark;
else
throw new Exception("I really have no idea what you want to do here.");
This also looks wrong:
moduleOverallLvl4[moduleCounter].Text = modAvg.ToString();
You never tell us what moduleOverallLvl4 is, but here you're assuming it has the same size as what is returned by requiredLevelList(). Maybe they are in this particular case, but that is a dangerous assumption. If these values are related, moduleOverallLvl4 should be contained in whatever class implements requiredLevelList, and you should have a method that assigns getModuleScoreOverall() to the correct element of moduleOverallLvl4.
If I wanted to swap out part of a statement with a variable i.e.
tempCube.transform.parent = row(var would need to go here ie an int that is iterated with a for loop).transform;
How would I write this. Sorry for the really basic question, I have been using other languages too long and now I have gone back to c# I have almost forgotten everything I had learned.
"(i)" is the bit I want to swap out with a variable
eg
for(int i = 1; i <= 3; i++){ print row*(i)*.transform; }
Console:
(1,2,3)
(2,3,4)
(4,5,6)
You mean like:-
row1.transform;
row2.transform;
row3.transform;
...
If so, no, you can't replace that text at runtime. You should use a collection. Ideally make an IEnumerable out of them and use foreach:-
foreach (var x in new { row1, row2, row3 ... })
{
x.transform;
}
I am not sure what you mean, i hope you want to specify the index, is this what you are looking for (index is the int you mentioned)
tempCube.transform.parent = row[index].transform;