98 points · by ehamberg · 14y ago · 71 comments
std::pair<double, double> findRoot(double a, double b, double c) {
if (a == 0.0)
throw std::invalid_argument("a has value 0.0!");
double root1 = (-b + sqrt(b*b - 4*a*c)) / (2*a);
double root2 = (-b - sqrt(b*b - 4*a*c)) / (2*a);
return std::pair<double, double>(root1, root2);
}
It seems too many C++ programmers see a problem and think "Hey, let's use classes!". #include <math.h>
#include <errno.h>
int findRoot(double a, double b, double c, double *root1, double *root2) {
double discriminant, q;
if (a == 0.0) {
return EDOM;
}
discriminant = b*b-4*a*c;
if (discriminant < 0) {
return EDOM;
}
q = -(b+copysign(sqrt(discriminant), b)) / 2;
*root1 = q/a;
*root2 = c/q;
return 0;
}
This style is quite in line with a number of math packages I've used in C. Since the author used a numerically unstable solution, I suspect there's a lack of domain inexperience in what library users expect from a math package. Eg., why would I go through the overhead of copying my input parameters to a temporary struct when I could just pass them directly to the function?Numeric code is really inappropriate for demonstration of new C++ features, as good (fast!) numeric code is most often C with templates.
template< typename T >
auto findRoots(T a, T b, T c) -> pair<maybe<complex<T>>, maybe<complex<T>>> {
typedef complex<T> C;
typedef maybe<C> Root;
typedef pair<Root, Root> Roots;
if (a == 0) {
if (b == 0)
return Roots(nothing, nothing);
else
return Roots(Root(-c / b), nothing);
} else {
auto d = C(b*b - a*c*4);
auto two_a = a*2;
return Roots(Root((-b + sqrt(d)) / two_a),
Root((-b - sqrt(d)) / two_a));
}
}
maybe is simply a templatized std::pair wrapper that lets you check if the returned value is valid (either via maybe.valid() or if(maybe)). All imaginary results are handled automatically via std::complex. nothing decomposes into an invalid maybe value of the appropriate type."Sometimes, the elegant implementation is just a function. Not a method. Not a class. Not a framework. Just a function."
https://twitter.com/#!/ID_AA_Carmack/status/5351230045120102...
I always found it absurd that some languages force you to write "Math.cos(...)".
I disagree. Namespaces are a good thing. The "Foo dot bar" syntax is just commonly associated with class member access. I think it's a lot better to have to explicitly refer to where a function comes from (as long as it doesn't devolve into retarded Java-style verbosity, ie "Foo.bar.baz.spam.eggs..."). Though it's nice to have a way to omit the namespace, ie C++'s "using namespace Foo" or Python's "from Foo import bar". I just think that the sane default is to use explicit namespaces.
constexpr tuple<double, double> Roots(double a, double b, double c)
{
return (a == 0.0) ? throw invalid_argument("a has value 0.0!") :
tuple<double, double>{
(-b + (sqrt((b * b) - 4 * a * c))) / 2*a,
(-b - (sqrt((b * b) - 4 * a * c))) / 2*a
};
} return /* ... */ throw invalid_argument("");
really valid C++11?[1] http://akrzemi1.wordpress.com/2011/05/06/compile-time-comput...
return a == ALPHA ? x :
a == BETA ? y :
a == GAMMA ? z :
throw ...;
Although that's not a style I'd recommend. #include <iostream>
#include <string>
#include <cmath>
using std::string;
using std::cout;
using std::endl;
static bool findRoots(
double a,
double b,
double c,
double &rootOne,
double &rootTwo,
string &errMsg
)
{
if(a == 0.0)
{
errMsg = "Parameter 'a' cannot be zero";
return(false);
}
double discriminant = b * b - 4 * a * c;
if(discriminant < 0.0)
{
errMsg = "Discriminant cannot be less than zero";
return(false);
}
double dSqrt = sqrt(discriminant);
double twoA = 2 * a;
rootOne = (-b + dSqrt) / twoA;
rootTwo = (-b - dSqrt) / twoA;
return(true);
}
int main()
{
double a[] = { 0.0, 2.0, 2.0 };
double b[] = { 1.0, 3.0, 1.0 };
double c[] = { 2.0, 2.0, 0.0 };
double rootOne;
double rootTwo;
string errMsg;
for(int n = sizeof(a) / sizeof(a[0]), i = 0; i < n; i ++)
{
cout << "a: " << a[i] << ", b: " << b[i] << ", c: " << c[i] << endl;
if(findRoots(a[i], b[i], c[i], rootOne, rootTwo, errMsg))
{
cout << rootOne << " " << rootTwo << endl;
}
else
{
cout << errMsg << endl;
}
cout << endl;
}
return(0);
} def findRoot(p:(Double,Double,Double)) = {
assert(p._1 != 0)
val n = sqrt(p._2*p._2-4*p._1*p._3)
val d = 2*p._1
( (-p._2+n)/d, (-p._2-n)/d )
}
----
scala> findRoot((6,-6,-36))
res0: (Double, Double) = (3.0,-2.0)why should they?
In a larger context, you might want to actually have an object/struct that represents a quadratic equation. The weird thing though was having an object for a quadratic equation and not having another object for its root (or more likely, either have a binomial class or just one generic polynomial class). I'm trying to think of a context where that makes any sense at all... and not finding it.
That's usually a result of people coming from Java doing C++ work.
Needless duplication of code; simple one-line declarations (i.e. a struct with three doubles) spread out over 5; empty constructors with trivial initializer lists defined outside the class header; needless empty destructors defined (again, outside the class declaration) for classes without virtual functions; "} else {" spread out across three lines (pet peeve of mine).
The disaster of an Error enumerant deserves a paragraph all by itself. It's got only two values, "OK" and "FAIL". Guess which one evaluates to boolean truth? (And yes, I'm aware of how errno and the like work -- but error codes tend to be something other than "FAIL").
This looks like code generated by an IT employee at a local soap manufacturing company, not something to be seriously considered by people interested in C++ evolution.
Too bad you go and ruin a perfectly reasonable comment with that crap.
I'm sorry I slandered your slander.
The one that is an error?
edit to avoid stringy flame thread: but it's a discussion on STYLE. If this was an example of how to write an error API, I wouldn't care (I probably wouldn't read it either). But it's a discussion about how C/C++ is written by presumably talented authors, and by inference how other people should write code. And the code sucks, sorry. And I'm horrified at your identification of dead code and needless whitespace as "syntactic fluff" not worthy of consideration as an important part of style.
"For the purposes of the exercise I’ve deliberately limited the amount of error checking; this isn’t meant to be industrial-strength code (so don’t gripe to me that I haven’t covered all the error cases!)"
I think it's pretty clear (at the very least, it's charitably inferrable) that the author is accustomed to errno-flavour error codes. Everything else you gripe about is just syntactic fluff* that makes no difference whatsoever to the analysis, and is dialect-invariant anyway.
* Edit: by syntactic fluff I mean that it has both the properties of being easy to mechanically change and that the given mechanical change wouldn't turn bad code into good. One can have strong feelings about the density of white space in code or the proper place of constructor definitions for a class not defined in a header file (I don't, but whatever), but when the solution to it is to run it through a program for a perfect result, I think it becomes not worth discussing.
I'm not sure what point it serves to compare debug mode executable sizes, but that should be clearly stated in the article. As other people stated, the final example really ought to lose the wrapping class in the spirit of C++11 brevity and functional decomposition.
http://en.wikipedia.org/wiki/Quadratic_equation#Floating_poi...
I imagine the size differences are overhead from bringing in STL and maybe template instantiation and are relatively fixed? I would have liked to see performance benchmarks as well as executable size to see if the program has gotten slower, faster, or remained basically the same.
If it were compiled with full optimizations and the final binaries stripped, they'd be much closer in size. Moreso if exceptions are disabled or if the class is replaced with a simple function taking/returning tuples.
Friends don't let friends use iostream.
[1]: http://llvm.org/docs/CodingStandards.html#ll_iostream
[2]: http://stackoverflow.com/questions/9371238/why-is-reading-li...
(A C++ fan would counter that they are faster than pointer-based generic algorithms like C's qsort and that you'd get the same code size manually typing it out.)
As for size, you're absolutely right, though for many scenarios that appears to be less and less a pressing concern. Perhaps the biggest drawback is compilation time.
What makes you think that a decent C compiler can't inline runtime-generic code using void* and virtual functions?
Sure, erasing types only so that the optimizer has to figure the information out again using constant propagation is far from optimal, but the underlying issue is actually source code inclusing vs modular compilation -- most of the speed gain of templates comes from the fact that it only works with the former, whereas C-code traditionally does the latter.
Even so, making heavy use of templates I have not yet found any major issues or that compile time has increased so drastically that it became a concern for the project.
Do note that instruction caches are not unlimited, though: bloated code does have a performance cost (sometimes, caches are hard.)
This is not even funny....
And packing three doubles in structures - good programming technique? Okay.. That's enough (it might be good sometimes, but not always)