Computer Science Canada

finding max value

Author:  JR [ Tue Oct 17, 2006 7:57 pm ]
Post subject:  finding max value

Hi in a part of my program i have a loop that does some basic math to calculate a number, now the loops stops when the number reachers zero, but the number starts increasing first then after it reaches a max number it will then start decreasing, its a basic math multiplication. I was wondering how i could get that maximum value and store it in a variable, what check do i need to use?

Author:  [Gandalf] [ Tue Oct 17, 2006 9:40 pm ]
Post subject: 

code:
if (currentNumber > currentMaxNumber) currentMaxNumber = currentNumber;

or if you include <cmath>.
code:
currentMaxNumber = max (currentNumber, currentMaxNumber);

Something along those lines. If you need more specific help, just be more specific in your next question. Wink

Author:  wtd [ Wed Oct 18, 2006 12:28 am ]
Post subject: 

It would be better to use something more C++-y. Smile

http://www.sgi.com/tech/stl/max.html

code:
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
   cout << max(3, 5) << endl;

   return 0;
}

Author:  bugzpodder [ Fri Oct 20, 2006 8:02 am ]
Post subject: 

[Gandalf] wrote:
code:
if (currentNumber > currentMaxNumber) currentMaxNumber = currentNumber;

or if you include <cmath>.
code:
currentMaxNumber = max (currentNumber, currentMaxNumber);

Something along those lines. If you need more specific help, just be more specific in your next question. Wink


the second way is 1.5 times as slow as the first

Author:  md [ Fri Oct 20, 2006 8:35 am ]
Post subject: 

bugzpodder wrote:
[Gandalf] wrote:
code:
if (currentNumber > currentMaxNumber) currentMaxNumber = currentNumber;

or if you include <cmath>.
code:
currentMaxNumber = max (currentNumber, currentMaxNumber);

Something along those lines. If you need more specific help, just be more specific in your next question. Wink


the second way is 1.5 times as slow as the first


You're sure? How did you measure it? 'Cause I'm pretty sure a function like max() is defined as inline; so there shouldn't be any speed difference.

Author:  bugzpodder [ Sat Oct 21, 2006 8:20 pm ]
Post subject: 

you are from waterloo?

if (currentNumber > currentMaxNumber) currentMaxNumber = currentNumber;

this does assignment only if the condition is satisfied.

the second way does assignment regardless. so the first approach is up to twice as faster than the second approach.

Author:  bugzpodder [ Sat Oct 21, 2006 8:21 pm ]
Post subject: 

or are you cornflake changing usernames :S

Author:  md [ Sat Oct 21, 2006 8:32 pm ]
Post subject: 

Yes, I was cornflake; my nick got changed for me Razz

And yes, your right; I see how it would definitely be a small bit slower. If max is a function that must be called then it'd be a lot slower however.


: