# Tag Info

46

If you're to implement something like this, you should first learn about how these things are done. I hope this doesn't sound too harsh. To explain it better, here is my variant of your code, with comparison to what C computes as e using expl(1): #include <stdio.h> #include <math.h> int main () { long double n = 0, f = 1; int i; for ...

23

Your mathematical criterion for equality has some issues. One important point to consider is that your "equality" is not transitive. In your code, you use a threshold of $\epsilon$ ($\epsilon = 5\times10^{-16}$ in your code, when the values have type double); you declare $x$ and $y$ to be equal to each other if $|x-y|\leq \epsilon$. Now suppose ...

20

DivisionMethod is a pretty vague/poor name for your method; any method with the word "method" in it should raise a "bad name" flag! Also, hard-coding the threshold into the function takes away flexibility. Perhaps I'd consider an optional parameter, like this: public static double RoundedDivision(double a, double b, double threshold = 0.6) Okay, not sure ...

17

This answer uses pointer-casting for type-punning just to save space. In practice keep using your union (safe in ISO C99, and in C++ as a GNU and MSVC extension) or memcpy (safe in C and C++). This pointer-casting is only safe in MSVC, or GNU-compatible compilers with -fno-strict-aliasing Initial approximation Packed bit fields are not only unnecessary ...

15

Your functions and their use are very curious: A function to determine if two values are similar should be symmetric in its arguments, and return a bool. A function determining the truth of a property should be called is@. similarValue is a bit of a puzzler, which is actually good as the functions behavior is very surprising. A conditional expression ...

14

Don't throw string literals directly. Instead throw an instance of std::exception or (even better) a subclass thereof (in this case, I would choose either std::domain_error or std::out_of_range). It makes it easier for people to catch using catch (std::exception&). The Celsius(Fahrenheit) constructor should probably take its argument by const reference. ...

14

First, you're calculating Math.Floor(div) twice. You have already stored it in temp (and why not give it a more clear name, like floor). Second, you don't need the fractional variable: if (div - floor > 0.6) etc. Third, Math.Ceiling in this case is equal to floor + 1; The rest is a matter of personal style. Some people would remove the braces and some ...

13

I would have gone (and actually have gone in production code) for a Temperature class providing methods to obtain the values in the different units. This makes the streaming output slightly trickier but avoids the code repetition and makes it easier to lets say add Kelvin to it. I'd also prefer to use C++11 in class member initializers for the min and max ...

13

There's a bit to say about this code, so I'll try to take it from the top and work my way down: Declare main() after your functions so you don't have to declare those function prototypes at the beginning of your source code. You shouldn't be printing anything from the functions other than main() here. You should be returning the values to main() and handle ...

13

Personally I'm not sure why you're working so hard... function validateNumber(valueToCheck) { return !isNaN(Number(valueToCheck)); } or the more complete version from the question you've linked: function validateNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } JavaScript already has a number parser. This will allow values like '...

13

Naming Avoid single-letter or shortened form variable names. Extra characters on a variable's name are free, and work wonders for a maintenance programmer down the line. e.g. double n = 0; would better be: double output = 0; Additionally, I'm not sold on the name GetDoubleValue. At no point does this method retrieve the value from anywhere. What this ...

12

Out parameters in C++ In C++, you should almost never use out parameters (variables taken by reference and used to return a value from a function), you can read this excellent article by Eric Niebler. There are few cases where out parameters can make sense: When you want your return to be fast. And even then, return value optimization and move semantics ...

12

Wrong increment First, there is a bug in your main loop. This line: add ebx, 1 should be: add ebx, 4 because you are operating on 4 floats at a time. Right now, you are doing array elements [0..3] following by [1..4]. On my computer the program crashed because it had a problem doing an unaligned load. Simplify divide by 4 This part ...

12

I'm just going to break this down by the method. double similarValues(double valueBigger, double valueSmaller) { if ((valueBigger - valueSmaller) < 0.01) { return 1; //Return 1 if the values are similar } else { return 0; } } Since we're only interested on the truth value result here, we should use a boolean return to ...

11

You have committed a grave error here with operator precedence, which should have easily been caught with simple testing: X1 = Sector4Arithmetic / 2 * a; The variable names SectornArithmetic are bizarre. Most of those intermediate results don't need to be assigned to a variable. The most complex intermediate result, b * b - 4 * a * c, has a standard name:...

11

FP overflow A ridiculously long fractional part causes decplace to reach inf, and the perfectly valid number is converted to nan. Testing for NAN and INF Using strncmp would be much more clear. DRY The integer conversion loop is repeated at least twice (for whole part and exponent). It is a strong indication that you need to factor it out into a function. ...

10

Do you really need a new implementation for floating-point numbers comparison? java.math.BigDecimal may be useful for FP numbers comparison with its compareTo(arg) method. areEqual(args...) overloading seems too repetitive. You may consider redefining them using generics in a single method. An example with minor changes in the original code: public static &...

10

Bug If I convert "0e+1", I will get back 1, because of these lines: /* if the user types a string starting from e, make the base be 1 */ if (a == 0) a = 1; That check can't just be a == 0 because the part before the 'e' may be 0 as in my example. One way to fix this is to check if the string begins with an 'e' before parsing any digits ...

10

Don't use #define!!! There are much better techniques for all use cases of #define in C++. #define DPOINT '.' // Why not char constexpr dPoint = '.'; #define DIGITS 18 //significant digits of the number (mantissa) // Why not int constexpr digits = 18; Not sure this is allowed (pretty sure its illegal). #ifndef INT_MAX #define INT_MAX 2147483647 #endif //...

9

My first reaction was the same as ChrisWue's: consider using a single Temperature class instead. For example here is an example of a (C#) class handle angle units (i.e. radians and degrees). Alternatively, the repetition/duplication between the two classes could perhaps be avoided with a common base class or by using templates. Still, does the repetition ...

9

Simplify the input parsing I don't see a purpose for this part: while (!(input = std::cin.peek()) && input != '\n') { if (std::isalpha(input) || std::isspace(input)) std::cin.ignore(); } I suppose your intent was to ignore alphabetic characters at the beginning of the input, but it doesn't work for me. And I don't think it's necessary anyway. ...

9

Nick's answer is great for style points, I just wanted to make you aware of a bug in your implementation: char.IsDigit(c) will return true for numerical digits not in the Western Arabic numerals (0 1 2 3 4 5 6 7 8 9). It's obscure but it will cause your program to fail. E.g. var answer = GetDoubleValue("12345०7.56"); // DEVANAGARI DIGIT ZERO // answer = ...

9

In general we want to initialize a variable directly to the value it needs, rather than to a temporary "invalid" value. This reduces complexity, and helps to prevent the accidental use of the "invalid" value as if it were a real input. We should also put variable declarations as close to the point of use as practical. (e.g. z could be declared at the point ...

9

FYI, in IEEE754 sqrt is a "basic" operation that's required to be correctly-rounded (rounding error <= 0.5ulp), same as + - * /. Hardware FPUs (I think) always provide sqrt if they provide the other operations, especially division which is typically implemented similarly (and with similar performance). NR iterations each involving a division are not ...

8

Your algorithm uses intermediate numbers that are very large and very small, and they are therefore difficult for computers to work with. For example, 32! ≈ 2.6313 × 1035, which is well beyond LONG_MAX (which may be as small as 231 - 1 ≈ 2 × 109). Basically, once n is large enough (maybe 13, maybe 21), factorial(n) returns a "random" number. Since your ...

8

In this case, your performance will not be terrible, but, for really large arrays you may run in to problems. Also, there is a bug in your code... what if the input array is empty? Then you will get an ArrayIndexOutOfBoundsException on: float largeNumber = numbers[0]; There is always more than one way to do things, but, I want to post an answer here ...

8

Two-dimesional array Your first function can be aggressively reduced by replacing cI and friends by a 2D array: float *Receiver::parse_pid_substr(char* buffer) { static float pids[8]; memset(pids, 0, 8*sizeof(float) ); char rgcPIDS[8][32]; size_t i = 0, c = 0, p = 0; for(; i < strlen(buffer); i++) { if(buffer[i] == '\0') { break; ...

8

The other answers are good. I would add to them: Show us your test cases and their results; we can criticize them as well and show you what test cases you should be using. Do you find it a little bit strange that DivisionMethod(10, 7) is 1 but DivisionMethod(-10, 7) is -2 ? I would expect that changing the sign of an operand should change the sign of the ...

8

I feel that rofl pretty well covered how this could be done differently, but I want to point out what I feel to be an issue. You really shouldn't be formatting the decimal results as a string. Formatting should be done in whatever application consumes the data you're sending it. As a user, I would be pretty upset to receive a "percentage" that I couldn't do ...

8

Please make the class final to let noone inherit the class. Nobody would expect a AsserationError if he can inherit the class. Everyone who inherit the class would have duplicate javadoc. Please throw a RuntimeException or an IllegalStateException because the javadoc matches better. ;P let me miss seriousness. i miss strictfp at the class definition ...

Only top voted, non community-wiki answers of a minimum length are eligible