12 ms·
Let me give one other way of doing it: "C++ without classes" std::pair<double, double> findRoot(double a, double b, double c) { if (a == 0.0)
by alextgordon 15y ago
Let me give one other way of doing it: "C++ without classes"
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!".
- matthavener 15y agoReminds me of one of my favorite all time John Carmack tweets: "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/53512300451201024 https://twitter.com/#!/ID_AA_Carmack/status/5351230045120102...
- marshray 15y agoExactly. The function is perhaps the most powerful and useful abstraction in all of computer science. I always found it absurd that some languages force you to write "Math.cos(...)".
- slowpoke 15y ago>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.
- marshray 15y agoI don't think everyone should always use explicit namespaces everywhere. But in this case "Math" isn't even a namespace! It's a class of which cos() is a static member. http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#cos%28double%29 http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html...
- pauldino 15y agoThankfully Java 5 added 'import static' which lets you pretend classes are namespaces. http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html http://docs.oracle.com/javase/1.5.0/docs/guide/language/stat...
- marshray 15y agoThanks for that info. Anyone know if C# has something similar? From the linked docs: So when should you use static import? Very sparingly! To me, it sort of confirms the point that these inelegant features are necessary because the language doesn't support fundamental primitives like plain functions and named constants without a superfluous object definition.
- pauldino 15y agoThe CLI itself actually supports unadorned functions, but C# doesn't provide a way of writing them, or using directly them without resorting to reflection. I'm pretty sure C++/CLI lets you use and write standalone functions in managed code, and come to think of it I imagine F# would too. Also it's not an exact equivalent, but C# extension methods can often be used instead of static methods.
- atesti 15y agoYou can mark a class as static, then it will only allow static functions or members: static class Math { static int Pow(int a,int b) {...} }
- sukuriant 15y ago
- colomon 15y agoHa! I was going to post a Perl 6 version of this to show how much shorter it is when you don't go through all the rigamarole, but of course you remind us that it's that short in C++ if you do it in a sensible manner. Bravo.
- alexchamberlain 15y agoWhat's std::pair if it isn't a class?
- alextgordon 15y agoThere's nothing inherently wrong with classes. I use classes occasionally. But if you don't need to use one for everything. C++ isn't Java.
- ajross 15y agoSurely alextgordon's point was that defining a solution in terms of a class where a function was more appropriate was bad, not that use of existing abstract types is to be avoided.
- YogSothoth 15y agoa struct ;-) ... http://www.cplusplus.com/reference/std/utility/pair/ http://www.cplusplus.com/reference/std/utility/pair/
- alexchamberlain 15y agoI was waiting for that! :-P
- dxbydt 15y agoif you are comfortable with returning tuples, perhaps the inputs should be a tuple as well... 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)
- ajross 15y agoNot sure how we got to Scala, but in (non-varargs) C linkage the whole metaphor of "funtion arguments" is inherently a "tuple" to begin with. They only exist in tandem with each other, never in isolation. There's no real value I can see to trying to double-abstract it.
- nooop 15y ago> if you are comfortable with returning tuples, perhaps the inputs should be a tuple as well... why should they?
- YogSothoth 15y agoI'm with you alex, I tend to only use classes when I've got to maintain state, I just use a function otherwise. Here's how I'd likely code this ... #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); }
- VMG 15y agothank you for your answer, but next time better use something like http://gist.github.com http://gist.github.com
- alexk7 15y agoThis is even more C++11-ish: (Not tested, my compiler at work is not C++11 compliant.) 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 }; }
- jsnell 15y agoThat's just horrible. The readability of the function has been totally destroyed by conditional operator. What's the imaginary C++11-ish benefit?
- alexk7 15y agoWith constexpr, if the parameters are constants, the whole computation can happen at compile-time. The line is somewhat harder to read for people not used to functional programming, but unfortunately, constexpr functions are required to have a single expression.
- hythloday 15y agoIs return /* ... */ throw invalid_argument(""); really valid C++11?
- alexk7 15y ago"The rules for conditional operator are quite sophisticated and one of them says that if one of the sub-expressions is a throw expression, the type of the entire conditional operator is that of the other sub-expression." [1] [1] http://akrzemi1.wordpress.com/2011/05/06/compile-time-computations/ http://akrzemi1.wordpress.com/2011/05/06/compile-time-comput...
- hythloday 15y agoThanks for both your and pdw's explanations...the lovely thing about C++ is that there's always something new to learn. ;)
- dalke 15y agoThe linked page say "The typical C solution is to create a structure to hold the quadratic equation parameters." That seems like sticking 'C with classes' into something which doesn't need classes in the first place. Why wouldn't the standard solution for C use pointers to pass the return parameters? Something like: #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?
- ansgri 15y agoMake it a template (parameterized with coefficient and solution type) and you'll get very generic and efficient solution across all mentioned 'dialects' of c(++). It has the added bonus that this routine can be converted to vector form almost without breaking the interface: just make a, b, c pointers and specify length. And you can specialize templates when you'll want to rewrite float32_t-version in assembly. Numeric code is really inappropriate for demonstration of new C++ features, as good (fast!) numeric code is most often C with templates.
- ajax77 15y agoA slight variation with neither error codes nor exceptions. 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.
- naner 15y agoIt seems too many C++ programmers see a problem and think "Hey, let's use classes!". That's usually a result of people coming from Java doing C++ work.
- eps 15y agoThat's usually a result of people erroneously thinking of themselves as C++ experts.
- cbsmith 15y agoHonestly, given the problem context, a function is obviously the way to go. There isn't enough other context to give you a guideline for having an object model. 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.