|
|
A tongue-in-cheek approach:
Averaging...the easy way.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
I've taken the link provided above (about cumulative average) as an inspiration to calculate the average incrementally, in a way that no intermediate value gets larger than about three times the maximum absolute value being added. Since I wasn't sure about various effects, such as the current average going negative, I added some test code and asserts to verify it actually works as intended. See the code below:
#define TEST_RANGE
#ifdef TEST_RANGE
#include <assert.h>
void minmax(const double newval, double&minv, double&maxv) {
if (newval < minv)
minv = newval;
else if (newval > maxv)
maxv = newval;
}
#endif
template <class basetype, class container_iterator>
basetype average(const container_iterator& start, const container_iterator& end) {
basetype cumulated_average = 0;
basetype cumulated_remainder = 0;
basetype addendum = 0;
#ifdef TEST_RANGE
double real_avg = 0.0;
double val_min = *start;
double val_max = *start;
double avg_min = cumulated_average;
double avg_max = cumulated_average;
double rem_min = cumulated_remainder;
double rem_max = cumulated_remainder;
#endif
long long n_values = 0;
for (auto pvalue = start; pvalue != end; ++pvalue) {
++n_values;
addendum = cumulated_remainder - cumulated_average + *pvalue;
cumulated_average += addendum/n_values;
cumulated_remainder = addendum%n_values;
#ifdef TEST_RANGE
real_avg += *pvalue;
assert((char)(n_values*cumulated_average + cumulated_remainder - real_avg) == 0);
minmax(*pvalue, val_min, val_max);
minmax(cumulated_average, avg_min, avg_max);
minmax(cumulated_remainder, rem_min, rem_max);
#endif
}
#ifdef TEST_RANGE
assert (fabs(n_values*cumulated_average - real_avg) < n_values);
real_avg /= (double)n_values;
#endif
return cumulated_average;
}
void test_average() {
char cvalues[] = { 13,7,-27, 34, -3, 22, 33, -1, 18, 29,
13,7,-27, 34, -3, 22, 33, -1, 18, 29,
13,7,-27, 34, -3, 22, 33, -1, 18, 29,
13,7,-27, 34, -3, 22, 33, -1, 18, 29,
13,7,-27, 34, -3, 22, 33, -1, 18, 29
};
auto cavg = average<char>(cvalues+0, cvalues+50);
}
The last line is how it's used. For passing the values, you can pass any pair of iterators that delimit the range, including simple pointers (as I've done here), provided that these iterators can be incremented and dereferenced. In this example, the cumulative average does go negative a few times, and the total sum adds up to 625, way above the maximum a char can hold.
Note that you may not use a signed type for n_values: I originally used a signed type, but then found that this led to some nasty signed/unsigned conversion effects. You could probably get rid of that with proper casting though.
P.S. these are the formulas I've used:
The general idea is to have two values that correspond to the rounded average, and the remainder of the division, like this:
Cum_avg(n) := sum(x1 ... xn) \ n
Cum_rem(n) := sum(x1 ... xn) % n
These two values then fulfil the follwing equation:
sum(x1...xn) = n*Cum_avg(n) + Cum_rem(n)
The values for the next iteration are then calculated based on the previous values like this:
Cum_avg(n+1) := sum(x1...xn+1) \(n+1)
= (sum(x1...xn)+xn+1) \(n+1)
= (n*Cum_avg(n)+Cum_rem(n)+xn+1) \(n+1)
= ((n+1)*Cum_avg(n)-Cum_avg(n)+Cum_rem(n)+xn+1) \(n+1)
= Cum_avg(n) + (-Cum_avg(n)+Cum_rem(n)+xn+1) \(n+1)
I've used a helper variable called addendum to hold the divisor of the second term. This term is just a sum of three values that are going to be in the normal value range, so the worst that can happen here is an overflow of that term. I still suspect that this can happen under certain circumstances, so the calculation of addendum may need some reworking!
The remainder of the next iteration is then simply the remainder of the division of addendum:
Cum_rem(n+1) := addendum % (n+1)
GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)
|
|
|
|
|
Hi,
I think I'm getting different behaviours with the code below for Release and Debug compiles.
FILE* in ;
err = fopen_s (&in, fileName.c_str(), "r");
if (!in) {
std::cerr << "cannot open input file '" << fileName << "'" << std::endl;
return;
}
char buff[1024];
while (fgets(buff, 1024, in)) {
std::string line=buff;
line is getting the characters ok when compiled in Debug. In Release though, line is BadPtr.
I guess I'm doing the initialization wrong, but I don't see why.
|
|
|
|
|
Perhaps this[^] link will help.
"the debugger doesn't tell me anything because this code compiles just fine" - random QA comment
"Facebook is where you tell lies to your friends. Twitter is where you tell the truth to strangers." - chriselst
|
|
|
|
|
My excuses for not answering during the weekend.
As suggested by some comment on the link you posted (thank you) the problem seems to be in the fgets function. It is storing senseless data in buff for Release, and then the std::string constructor can't make sense of it.
I will try with std::getline() .
|
|
|
|
|
I suspect there is something you are not showing us. I have just tried your code and it works in both Debug and Release modes.
|
|
|
|
|
It's possibly a configuration issue.
Meaning you've some configuration for Debug that you haven't done for Release.
«_Superman_»
I love work. It gives me something to do between weekends.
Microsoft MVP (Visual C++) (October 2009 - September 2013) Polymorphism in C
|
|
|
|
|
It is, quite probably.
fgets (not std::string constructor as I initially posted) is behaving different if I set different options for Optimization and Runtime Library in MSVS2005.
I can't make Release work like Debug though, even setting the same options.
|
|
|
|
|
Hi,
I'm working on a small libarary that will parse and modify a certain type of configuration file. As suggested by wise people (I think) I'd like to hide away the implementation and offer the user a set of functions to use the library.
I have questions mainly philosophical or concerning style. I'll put here my idea and it'd be very nice to get your opinions on it.
#ifndef CONFIGFILEAPI_H_INCLUDED
#define CONFIGFILEAPI_H_INCLUDED
#include <string>
#include <vector>
namespace cfgFileLib
{
std::string openConfigFile (const std::string & fileName);
bool isDefined (const std::string & symbol);
int howMany (const std::string & symbol);
bool getBool (const std::string & symbol);
int getInt (const std::string & symbol);
double getDouble (const std::string & symbol);
std::string getString (const std::string & symbol);
std::vector <bool> getAllBool (const std::string & symbol);
std::vector <int> getAllInt (const std::string & symbol);
std::vector <double> getAllDouble (const std::string & symbol);
std::vector <std::string> getAllString (const std::string & symbol);
}
#endif
- Does this design make sense in general?
- Do I put it all whithin a namespace?
modified 6-Aug-14 8:51am.
|
|
|
|
|
Have a look at Boost.PropertyTree[^]
I think it's a well designed library - it's worth taking a look at it's implementation.
>> Does this design make sense in general?
Normally you would create a class that is able to hold more than one configuration entry, and then something representing the various kinds of entries.
>> Do I put it all whithin a namespace?
That's usually a good idea
Best regards
Espen Harlinn
Espen Harlinn
Chief Architect - Powel AS
Projects promoting programming in "natural language" are intrinsically doomed to fail. Edsger W.Dijkstra
|
|
|
|
|
Thanks Espen. I'll take a look at Boost.PropertyTree
I didn't get what you meant by
Espen Harlinn wrote: Normally you would create a class that is able to hold more than one configuration entry, and then something representing the various kinds of entries.
|
|
|
|
|
Something structured somewhat like this:
class ConfigEntry
{
};
class ConfigNode : public ConfigEntry
{
typedef std::map<std::string,std::shared_ptr<ConfigEntry> > EntryMap;
EntryMap entryMap_;
};
class ConfigValue : public ConfigEntry
{
};
class StringConfigValue : public ConfigValue
{
std::string value_;
};
class IntConfigValue : public ConfigValue
{
int value_;
};
class ConfigFile : public ConfigNode
{
};
This way the EntryMap can hold std::string, int and nested ConfigNode objects.
Espen Harlinn
Chief Architect - Powel AS
Projects promoting programming in "natural language" are intrinsically doomed to fail. Edsger W.Dijkstra
|
|
|
|
|
If you're using this in C++ only, seems ok (let alone the preferences).
However, I'd do this:
- no namespace exports; be wary of linker decorations
- export just the needed functions, not all (i.e. the "public" interface)
- separate helpers from actors (i.e openConfigFile, isDefined vs getBool, getInt)
- do not return std::string or others from functions; rather, return just simple testable values (int, bool) and change to
bool openConfigFile(const std::string& filename, std::string& result); (or std::string* result)
- if you'll get this used in other places, favor a C-like interface and do the plumbing code, such as
BOOL WINAPI OpenConfigFileA(LPCSTR fileName, LPSTR* result);
or use VARIANTs is needed in VBS.
- or favor the COM-like exports with just structs with virtual pure functions and DllGetClassObject-like creators.
There are many things to consider. I'm using sometimes even paper and pen to weight all these.
|
|
|
|
|
Hi I am beginner in c++ , I have a console project and want to convert it to windows application , after 6-7 days trying I couldn't convert it and when I compile project I have many more errors
This is my console project: http:
Please convert it for me to windows gui application to help me thanks a lot
|
|
|
|
|
|
Don't convert console apps, rather follow this short list:
1. Make sure key logic is not in same file as main.
2. Create a dialog app using Visual Studio
3. Add files from step 1
4. Hook up functionality
Of course 4 is the complicated part since how Windowed apps work is different from Console. As previously suggested, if you don't know how windowed apps work, get educated. Petzold isn't a bad starting point, though will only take you so far.
|
|
|
|
|
Just another homework, no effort from poster, just "I can't do it" and a link.
We're supposed to invest time and effort to offer you solutions for free, in our time, so you can get an A and forget about C++ or something? RTFM.
|
|
|
|
|
in this code?from where i need to understand that is deleting something?
void Database_delete(struct Connection *conn, int id)
{
struct Address addr = {.id = id, .set = 0};
conn->db->rows[id] = addr;
|
|
|
|
|
As far as I know, this is not valid C++ code.
THESE PEOPLE REALLY BOTHER ME!! How can they know what you should do without knowing what you want done?!?!
-- C++ FQA Lite
|
|
|
|
|
|
Yes, you are right.
THESE PEOPLE REALLY BOTHER ME!! How can they know what you should do without knowing what you want done?!?!
-- C++ FQA Lite
|
|
|
|
|
This[^] thread might help. It looks as though there are members of the Address struct one called set and it's getting initialized to 0, and another called id and it's getting initialized to the given integer id.
"the debugger doesn't tell me anything because this code compiles just fine" - random QA comment
"Facebook is where you tell lies to your friends. Twitter is where you tell the truth to strangers." - chriselst
|
|
|
|
|
yes,but by the name of function says(database_delete),this function must delete something,and i don't know how it is deleting something
|
|
|
|
|
Just a guess, perhaps set is some kind of flag marking a record as inactive or something, as opposed to actually deleting a record. What a functions name is and what it actually does may be two different things. What's needed here I believe is some useful comments.
"the debugger doesn't tell me anything because this code compiles just fine" - random QA comment
"Facebook is where you tell lies to your friends. Twitter is where you tell the truth to strangers." - chriselst
|
|
|
|
|