Skip to content

string -> number conversions #299

Closed

Description

@yakra

Py: We can avoid crashes when attempting to convert a non-numeric string to a number by using try/except/else.

Some (but not all) applications:

  • Tier values in systems.csv
  • The MALFORMED_LAT & MALFORMED_LON datachecks could be rewritten to be more simple & compact. And maybe it might even help efficiency in the process.
  • C++: malformed URL datachecks already use strtod. A similar wasted opportunity for brevity and probably speed.
  • search cplusplus/ for strto
  • search siteupdate.py for int( and float(

Activity

  1. yakra commented on Apr 12, 2020

    @yakra
    ContributorAuthor

    Or not. Both C++ and Python will successfully convert scientific notation such as -7.0752597e+1, or values of +- INF or NAN.
    C++ will parse hex values such as -0x66.C; Python will not.

    It makes no sense to allow these esoteric strings that would not be produced by wptedit. A stray e or E could find its way into a latitude or longitude string just as easily that a did in rou.dj102k.wpt that one time. A NAN or INF could have unintended consequences farther down the line.

    C++, we can clean up using an inline function.
    Python, a function may harm performance by introducing more passes by value.

    • In either case, efficiency can be improved over what we have now.
  2. yakra commented on Apr 13, 2020

    @yakra
    ContributorAuthor

    C++: We're down 49 lines in the Waypoint ctor itself, 29 lines overall. Any increase in speed I might see may just be confirmation bias, but it's not any slower. :) The code should be faster in theory, at any rate...

    • Not checking for a - at the beginning
    • Not checking whether we're past the beginning when checking for - thereafter.
    • A couple < and >s should be more efficient than using strchr.
    inline bool valid_num_str(const char* c, const char delim)
    {	size_t point_count = 0;
    	// check initial character
    	if (*c == '.') point_count = 1;
    	else if (*c < '0' && *c != '-' || *c > '9') return 0;
    	// check subsequent characters
    	for (c++; *c && *c != delim; c++)
    	{	// check for minus sign not at beginning
    		if (*c == '-') return 0;
    		// check for multiple decimal points
    		if (*c == '.')
    		{	point_count += 1;
    			if (point_count > 1) return 0;
    		}
    		// check for invalid characters
    		else if (*c < '0' || *c > '9') return 0;
    	}
    	return 1;
    }

    Python: I didn't really expect it to help much, but for giggles I implemented pretty much a carbon copy of the C++ code:

    def valid_num_str(data):
        point_count = 0
        # check initial character
        if data[0] == '.':
            point_count = 1
        elif data[0] < '0' and data[0] != '-' or data[0] > '9':
            return False
        # check subsequent characters
        for c in data[1:]:
            # check for minus sign not at beginning
            if c == '-':
                return False
            # check for multiple decimal points
            if c == '.':
                point_count += 1
                if point_count > 1:
                    return False
            # check for invalid characters
            elif c < '0' or c > '9':
                return False
        return True

    It turned out to be a tiny bit faster, a bit surprising since I'd expect there to be more passing around strings by value, and more copying. I don't really know how Python works under the hood, or what optimizations the interpreter may have. Maybe the same changes made in the C++ version were enough to have a bigger effect here...

    • In that vein, does slicing the string (for c in data[1:]) create a new string object? Would it be faster to use a numeric index range, and iterate thru the chars in the existing string? Something to try out. (Slower than the original!)
    • Can we still improve speed by inlining this code, and avoiding the function call & string copying? If I can get a decent speedup Reading waypoints for all routes, I'll take that over brevity. (Nope. Maybe a bit slower; within margin of error. The tidy version is also the fastest.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions