How can I find the difference between 2 values in C#? - c#

I am working with an Oscillator that fluctuates between 10.000000 and -10.000000
The value changes say every 5 minutes. I want to find the difference between the current value and the value of 5 minutes ago. Here is my logic.
1 bar ago (1BA)= -.2
Current bar (CB) = .3
Wouldn't I get a value of 1 if I did something like:
Abs(CB) - Abs(1BA) = .3 - .2 = 1
Whereas:
Abs(CB- 1BA) = .3 - -.2 = 5
I want to simply calculate the difference between the move of the oscillator from one time frame to another. Am I applying the Abs with the right logic in mind?
Here is my actual code, please assume my method being called is correct:
if (Oscillator(PoFast, PoSlow, PoSmooth)[0] >
Oscillator(PoFast, PoSlow, PoSmooth)[3]
&& Math.Abs(Oscillator(PoFast, PoSlow, PoSmooth)[0] -
Oscillator(PoFast, PoSlow, PoSmooth)[3]) > .25)

Of the two, Abs(CB-1BA) would be correct, since there was a change of .5 between the two readings.
EDIT: To make it more readable, and assuming you're getting double values, you'd do something like this, but with error checking, and probably making the .25 a variable.
double[] values = Oscillator(PoFast, PoSlow, PoSmooth);
double currentBar = values[0];
double oneBarAgo = values[3];
if (currentBar > oneBarAgo && Math.Abs(currentBar - oneBarAgo) > .25)
{
// do something
}

Your logic, Abs(CB-1BA) is correct.
As an aside, if you're not a developer do you really think you should be writing C# code to trade futures contracts? They're risky enough to trade at the best of times, never mind when you're writing code to do it and you're not a developer!!!!

Related

Need help figuring out what I'm doing wrong in my if statement

I'm still learning C# with Windows Forms and I would like some help with my if statement.
The variables are fixed so there is going to be no user input other than them just clicking one button. Where my issue begins is at the beginning of the if statement.
VS(Visual Studios) constantly says that the half and calc in the condition, and the hours for the conversion to string are all unassigned local variables.
Then in the else statement where the math equation is, VS keeps saying that "hours" cannot be converted from double to hours.
I dont know what that means because I already declared them. Then it says the thirtheenpercent cannot be declared in the scope because it has already been declared. I dont know why it's saying this because this double is not supposed to change.
Can someone help me and explain why I am getting these errors?
Any help would be greatly appreciated.
decimal onecup = 130;
decimal thirtheenpercent;
decimal hours=0;
decimal half=130/2;
decimal calc=0;
while (onecup>half)
{
thirtheenpercent = (onecup * 13) / 100;
calc =onecup-thirtheenpercent;
onecup=calc;
hours++;
} mtbHalf.Text = Convert.ToString(hours)+" Hours.";
while (!(hours==24))
{
thirtheenpercent = (onecup * 13) / 100;
calc = onecup - thirtheenpercent;
onecup = calc;
hours++;
} mtbOnecup24.Text = Convert.ToString(Math.Round(calc,2)) + " mg.";
//While i was running this program, i ran into some conflictions with my already declared variables for my last while loop so i created some new ones.//
decimal thirtheenpercent2;
decimal calc2 = 0;
decimal onecup2 = 130;
int hours2 = 0;
while (!(hours2 == 24))
{
thirtheenpercent2 = (onecup2 * 13) / 100;
calc2 = onecup2 - thirtheenpercent2;
onecup2 = calc2;
hours2++;
onecup2 = onecup2 + 130;
} mtbQuantity.Text = Convert.ToString(Math.Round(onecup2, 2)) + " mg.";
}
The hours variable is unassigned, in the code you posted. So that error seems correct to me.
The code example is incomplete, but given what you've posted it does not appear that half and calc are in fact unassigned. So the most likely explanation for that is that you are either misinterpreting the error message (i.e. it doesn't say what you say it says), or you are not sharing the correct code (i.e. the code you included isn't the code that's being compiled when the error occurs).
As far as the last errors, your program statement hours * thirtheenpercent = calc is not valid syntax. The compiler will probably try to interpret that as a variable declaration, where hours is the type and the thirtheenpercent variable is being declared as a pointer to that type, initialized with the value held by the variable calc.
That's clearly not what you meant, and of course since hours is not a type, there's no way for the statement to compile successfully.
Possibly you meant calc = hours * thirtheenpercent? It's hard to tell from your question.
You seem to have other algorithmic issues. But without seeing the actual specification for what your code is supposed to do, it's hard to know for sure what the code should look like. Based on the comments, it's doubtful the algorithm would ever work as you seem to want it. You start with 13% of 130, and then (maybe) iteratively work through the multiples of that value. But no multiple of 13% is equal to 50%, so no multiple of (13% of 130) can be equal to (50% of 130).
On top of that, as commenter Ed Gibbs says, dealing with floating point, it's entirely possible that half and calc will never equal each other even the algorithm made sense. You could get extremely close, but not where the two values actually compare as identical.

How to shrink this particular if lines(messy) by using "?" operator

I am working on a project where I have to look into someone else's code and modify it.
However since many classmates in my class are quite new to program, many have such a messy organization.
The code that I am assigned to improvise has a lot of flaws and messy redundant lines.
I am trying my best to clean them up, however due to my inexperience, I find it hard to clean them up.
Lines such as
if (turnElapsed[1] == 2)
{
turnElapsed[0] += 1;
turnElapsed[1] = 0;
}
turnElapsed[1]++;
looks quite redundant to me.
I believe, and there must be a better way to write a simple version of it.
so I tried the code below but it seemed to not work properly.
turnElapsed[0] += (turnElapsed[1]++ == 2) ? 1 ; 0 ;
turnElapsed[1] = (turnElapsed[1] == 2 ) ? 0; turnElapsed[1];
Firstly, you are using ; as separator instead of : which is a syntax error. Secondly, you're incrementing turnElapsed[1] on the first line, which means that when it reaches the second line it will no longer equal 2 - that's different to the original logic. This is why your version does not work properly.
However, if you did fix those errors I don't think your code would be easier to read. The original is more readable, because it expresses the intention more clearly. You can read that and verbalise it as "if turnElapsed[1] is 2 then ...". Your alternative takes fewer lines, but is more "cryptic". Another advantage of the original code is that you can put a breakpoint inside the braces if you wanted to break when the if condition was true - you cannot do that with the ternary operator (?).
Your problem is that it is not readable and comprehensible. That is why you don't see your bug.
The bug is that you don't increment in the second version. Try this
turnElapsed[0] += (turnElapsed[1]++ == 2) ? 1 : 0 ;
turnElapsed[1] = ((turnElapsed[1] == 2 ) ? 0; turnElapsed[1]) + 1;
Aren't you just keeping a binary number in turnedElapsed, with the most significant bit in turnElapsed[0]? A much better version of the code would be:
long turnElapsed;
...
turnElapsed++;
Or, if you really don't want to start messing with bits:
turnElapsed[0] += turnElapsed[1]
turnElapsed[1] = (1 + turnElapsed[1]) % 2
EDIT: Apparantly turnElapsed[1] is 0 or 1, and turnElapsed[0] is incremented every time turnElapsed changes from 1 to 0. So you have the following:
long number;
...
number++;
turnElapsed[0] = number/2;
turnElapsed[1] = number%2;
No need for ifs, ?:'s or anything else. In fact, you don't even need the array.

Sorting numbers array issue

Yesterday at work I set out to figure out how to sort numbers without using the library method Array.Sort. I worked on and off when time permitted and finally was able to come up with a basic working algorithm at the end of today. It might be rather stupid and the slowest way, but I am content that I have a working code.
But there is something wrong or missing in the logic, that is causing the output to hang before printing the line: Numbers Sorted. (12/17/2011 2:11:42 AM)
This delay is directly proportionate to the number of elements in the array. To be specific, the output just hangs at the position where I put the tilde in the results section below. The content after tilde is getting printed after that noticeable delay.
Here is the code that does the sort:
while(pass != unsortedNumLen)
{
for(int i=0,j=1; i < unsortedNumLen-1 && j < unsortedNumLen; i++,j++)
{
if (unsorted[i] > unsorted[j])
{
pass = 0;
swaps++;
Console.Write("Swapping {0} and {1}:\t", unsorted[i], unsorted[j]);
tmp = unsorted[i];
unsorted[i] = unsorted[j];
unsorted[j] = tmp;
printArray(unsorted);
}
else pass++;
}
}
The results:
Numbers unsorted. (12/17/2011 2:11:19 AM)
4 3 2 1
Swapping 4 and 3: 3 4 2 1
Swapping 4 and 2: 3 2 4 1
Swapping 4 and 1: 3 2 1 4
Swapping 3 and 2: 2 3 1 4
Swapping 3 and 1: 2 1 3 4
Swapping 2 and 1: 1 2 3 4
~
Numbers sorted. (12/17/2011 2:11:42 AM)
1 2 3 4
Number of swaps: 6
Can you help identify the issue with my attempt?
Link to full code
This is not homework, just me working out.
Change the condition in your while to this:
while (pass < unsortedNumLen)
Logically pass never equals unsortedNumLen so your while won't terminate.
pass does eventually equal unsortedNumLen when it goes over the max value of an int and loops around to it.
In order to see what's happening yourself while it's in the hung state, just hit the pause button in Visual Studio and hover your mouse over pass to see that it contains a huge value.
You could also set a breakpoint on the while line and add a watch for pass. That would show you that the first time the list is sorted, pass equals 5.
It sounds like you want a hint to help you work through it and learn, so I am not posting a complete solution.
Change your else block to the below and see if it puts you on the right track.
else {
Console.WriteLine("Nothing to do for {0} and {1}", unsorted[i], unsorted[j]);
pass++;
}
Here is the fix:
while(pass < unsortedNumLen)
And here is why the delay occurred.
After the end of the for loop in which the array was eventually sorted, pass contains at most unsortedNumLen - 2 (if the last change was between first and second members). But it does not equal the unsorted array length, so another iteration of while and inner for starts. Since the array is sorted unsorted[i] > unsorted[j] is always false, so pass always gets incremented - exactly the number of times j got incremented, and that is the unsortedNumLen - 1. Which is not equal to unsortedNumLen, and so another iteration of while begins. Nothing essentially changed, and after this iteration pass contains 2 * (unsortedNumLen - 1), which is still not equal to unsortedNumLen. And so on.
When pass reaches value int.MaxValue, it the overflow happens, and next value the variable pass will get is int.MinValue. And the process goes on, until pass finally gets the value unsortedNumLen at the moment the while condition is checked. If you are particularly unlucky, this might never happen at all.
P.S. You might want to check out this link.
This is just a characteristic of the algorithm you're using to sort. Once it's completed sorting the elements it has no way of knowing the sort is complete, so it does one final pass checking every element again. You can fix this by adding --unsortedNumLen; at the end of your for loop as follows:
for(int i=0,j=1; i < unsortedNumLen-1 && j < unsortedNumLen; i++,j++)
{
/// existing sorting code
}
--unsortedNumLen;
Reason? Because you algorithm is bubbling the biggest value to the end of the array, there is no need to check this element again since it's already been determined to be larger the all other elements.

Changing variables outside of Scope C#

I'm a beginner C# programmer, and to improve my skills I decided to give Project Euler a try. The first problem on the site asks you to find the sum of all the multiples of 3 and 5 under 1000. Since I'm essentially doing the same thing twice, I made a method to multiply a base number incrementally, and add the sum of all the answers togethor.
public static int SumOfMultiplication(int Base, int limit)
{
bool Escape = false;
for (int mult = 1; Escape == true; mult++)
{
int Number = 0;
int iSum = 0;
Number = Base * mult;
if (Number > limit)
return iSum;
else
iSum = iSum + Number;
}
regardless of what I put in for both parameters, it ALWAYS returns zero. I'm 99% sure it has something to do with the scope of the variables, but I have no clue how to fix it. All help is appreciated.
Thanks in advance,
Sam
Your loop never actually executes:
bool Escape = false;
for (int mult = 1; Escape == true; mult++)
Escape is set to false initially, so the first test fails (Escape == true returns false) and the body of the loop is skipped.
The compiler would have told you if you were trying to access variables outside of their defined scope, so that's not the problem. You are also missing a return statement, but that is probably a typo.
I would also note that your code never checks if the number to be added to the sum is actually a multiple of 3 or 5. There are other issues as well (for example, iSum is declared inside of the loop and initialized to 0 after each iteration), but I'll let you work that one out since this is practice. The debugger is your friend in cases like these :)
EDIT: If you need help with the actual logic I'll be happy to help, but I figure you want to work it out on your own if possible.
As others have pointed out, the problem is that the control flow does not do what you think it does. This is a common beginner problem.
My suggestion to you is learn how to use your debugger. Beginners often have this strange idea that they're not allowed to use tools to solve their coding problems; that rather, they have to reason out the defect in the program by simply reading it. Once the programs become more than a page long, that becomes impossible for humans. The debugger is your best friend, so get to know its features really well.
In this case if you'd stepped through the code in the debugger you'd see that the loop condition was being evaluated and then the loop was being skipped. At that point you wouldn't be asking "why does this return zero?", you'd be asking "why is the loop body always skipped?" Clearly that is a much more productive question to ask since that is actually the problem here.
Don't write any code without stepping through it in the debugger. Watch every variable, watch how it changes value (the debugger highlights variables in the watch windows right after they change value, by the way) and make sure that the control flow and the variable changes are exactly as you'd expect. Pay attention to quiet doubts; if anything seems out of the ordinary, track it down, and either learn why it is correct, or fix it until it is.
Regarding the actual problem: remember that 15, 30, 45, 60... are all multiples of both three and five, but you only want to add them to the sum once. My advice when solving Project Euler problems is to write code that is as like what you are trying to solve as is possible. Try writing the problem out in "pseudocode" first. I'd pseudocode this as:
sum = 0
for each positive number under 1000:
if number is multiple of three or five then:
add number to sum
Once you have that pseudocode you can notice its subtleties. Like, is 1000 included? Does the problem say "under 1000" or "up to 1000"? Make sure your loop condition considers that. And so on.
The closer the program reads like the problem actually being solved, the more likely it is to be correct.
It does not enter for loop because for condition is false.
Escape == true
returns false
Advice:
Using for loop is much simpler if you use condition as limit for breaking loop
for (int mult = 1; something < limit; mult++)
This way in most cases you do not need to check condition in loop
Most programming languages have have operator modulo division.
http://en.wikipedia.org/wiki/Modulo_operation
It might come handy whit this problem.
There are several problems with this code. The first, and most important, is that you are using the Escape variable only once. It is never set to false within your for loop, so it serves no purpose whatsoever. It should be removed. Second, isum is declared within your for loop, which means it will keep being re-initialized to 0 every time the loop executes. This means you will only get the last multiple, not the addition of all multiples. Here is a corrected code sample:
int iSum = 0;
for(int mult = 1; true; mult++)
{
int Number = Base * mult;
if(Number > limit)
return iSum;
else
iSum += Number;
}

Increase value over time using mathematical algorithm

I am writing a test tool which places a large amount of load on a network service. I would like this tool to start with little load and gradually increase over time. I am sure that there is some triganometry which can do this sort of calculation in one line of code but I am not a math guru (yet). Is there some sort of library (or simple algorithm) which can help with this calculation?
The code would ideally take a few arguments:
algorithm to use (determine how quickly the value increases
starting value
ending value (maximum)
time (amount of time between starting and ending value)
step (granularity in milliseconds)
So every [step] an event would be raised indicating what the value is at that point in time.
This is an ideal implementation though, so I am open to suggestion.
Any input would be greatly appreciated, thank you :)
EDIT:
Let me be more clear ... the amount which the value increases is not linear, it is a curve.
If you desire some form of saturation (see Sigmoid function), have a look at my answer here. Another common function shape would be linear or exponential growth. Just let me know if you need one of the later.
I think what you need is some easing function.
There is a set of famous easing functions created by Robert Penner. You may try to look at:
Tweener transition cheat sheets which visualize Robert Penner's equations.
Robert Penner's original code should be at his webpage.
value = (endValue - StartValue) / (time / stepSize) * currentStep;
heck just add one each time the timer goes off
If I understood correctly, why not do this (using the "variables" you defined):
You need to progress overall ending value - starting value values.
Using the time variable, you can figure out how much of an increase you want every millisecond (let's call this increase-amount).
Step just tells you how much time to "sleep" between each value you raise. Every time a new value is raised, you just do last-value + (milliseconds-since-last_step * increase-amount).
Note: I'm not sure why you need the first variable (algorithm to use), since it seems to me that its role is defined by the other variables.
Are you looking for something like this ? (in python, sorry, my C# is rusted at best)
Given you have a curve f that takes values from 0 to 1:
def my_stepper(f, start, end, time, step_size, current_step):
x = current_step * step_size / time
f_1 = f(1)
f_0 = f(0)
y = start + (end - start) * (f(x)- f_0) / (f_1 - f_0)
return y
for i in xrange(11):
# increment increases over time
print 'exp', my_stepper(math.exp, 100., 200., 10., 1., i)
# increment decreases over time
print 'log', my_stepper(lambda x: math.log(1+x), 100., 200., 10., 1., i)
Pseduo logic to your problem:
let the function be F(a+b*x) for given step x,
let the starting value is start,
let the ending value is end
let the starting time is 0 and final time is time
and InverseF is the inverse function of F.
when x=0, F(a)=start Hence a= InverseF(start)
when x=time, F(a+b*time)=end, Hence b=(InverseF(end)-a)/time which reduces to b= (inverseF(end)-inverseF(start))/time
Finaly for any x=step,
value is F(a+b*step) which is
nothing but
F( inverseF(start)+ (inverseF(end)-inverseF(start))/time * step )
is the answer.
For example if
F(x) is liner ie) f(x)=x
value = start+(end-start)/time*step
if F(x) is x*x, then
value = ( sqrt(start) + (sqrt(end)-sqrt(start))/time * step) * ( sqrt(start) + (sqrt(end)-sqrt(start))/time * step)
if F(x) is exp(x) then
value = Exp ( log(start) + (log(end)-log(start))/time*step )
if F(x) is log(x) then
value = Log( (exp(start) + (exp(end)-exp(start))/time*step )
and so on..
another approach without using inverse function is explained below.
let the function be a+b*F(x) for given step x,
let the starting value is start,
let the ending value is end
let the starting time is 0 and final time is time
then a+ b * F(0) = start and a + b * F(time) = end, on solving a & b,
you will get
value = start + (end-start) / (F(time)-F(0) ) * (F(x)-F(0) )
and for a step x,
value = start + (end-start) / (F(time)-F(0) ) * (F(step)-F(0) )
and I hope, any one of the above will solve your problem..
I'll reuse my answer to another question. The functions given for that answer will not spend much time doing low load, but quickly go to medium-heavy load and then increase load slower to reach maximum. If you need more values on the in the middle of the possible loads, or more values in the low load - just pass appropriate distribution function.
Given your input parameters I would call it like this:
Spread(startingValue, endingValue, time/step, x => 1-(1-x)*(1-x))
Sample algorithm functions:
FocusOnHighLoad = x => 1-(1-x)*(1-x)
FocusOnLowLoad = x => x * x
FocusOnMediumLoad = x => (1 + Math.Pow(x * 2 - 1, 3)) / 2
Sample output:
foreach (double load in Spread(50, 1000, 9, FocusOnHighLoad))
Console.WriteLine("Working with {0} load", load);
Working with 50 load
Working with 272.65625 load
Working with 465.625 load
Working with 628.90625 load
Working with 762.5 load
Working with 866.40625 load
Working with 940.625 load
Working with 985.15625 load
Working with 1000 load

Categories

Resources