check overflow for double in average calculation in C++ -



check overflow for double in average calculation in C++ -

i have implement standard deviation , variance in c++.

#include <iostream> #include <string> #include <math.h> class stddeviation { private: int max; double value[100]; double mean; public: double calculatemean() { double sum = 0; for(int = 0; < max; i++) sum += value[i]; // question 1. @ bottom. homecoming (sum / max); } double calculatevariane() { mean = calculatemean(); double temp = 0; for(int = 0; < max; i++) { temp += (value[i] - mean) * (value[i] - mean) ; } homecoming temp / max; } double calculatesamplevariane() { mean = calculatemean(); double temp = 0; for(int = 0; < max; i++) { temp += (value[i] - mean) * (value[i] - mean) ; } homecoming temp / (max - 1); } int setvalues(double *p, int count) { if(count > 100) homecoming -1; max = count; for(int = 0; < count; i++) value[i] = p[i]; homecoming 0; } double getstandarddeviation() { homecoming sqrt(calculatevariane()); } double getsamplestandarddeviation() { homecoming sqrt(calculatesamplevariane()); } };

here questions:

how create sure value of double doesn't overflow , homecoming zero. how can check don't cross max value of sum i.e., double maximum value?

are sure overflow concern? maximum value of double 1.7*10308. summing squares, still safe if values don't exceed ~10150. have such values?

more serious concern rounding errors. double keeps 17 important digits (52 important binary digits precise). if add together numbers differ in exponent, lower part of smaller affects digits beyond precision of result. extreme 1e20 + 1 == 1e20, because represent different numbers, require 20 important digits , don't have them. when it's possible you'll have lot of little numbers , few big ones, it's recommended add together little ones first.

c++

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -