I have an app I'd like to open up to an international audience & so I need to accept different units, to keep it simple let's say miles & kilometers.
I figured I've got 3 options:
Use Meteor's transform option on my collection
Use Simple Schema's autoValue
Manually adjust the value every time I send/receive it from the DOM
Store mi/km in different fields (take advantage of that NoSQL!)
?
What is the pattern you've found most useful? Any examples would be great.
For smaller units of measure like yards and meters, I would use an integer of centimeters. It can be converted to any unit larger than itself easily and you shouldn't have any issues with floats. On a scale of miles and kilometers, I'd store integers of meters.
As far as how to transform them back and forth, I'd keep that in the view, not the model. I'm not a meteor guy so I'm not sure how that translates, but I'm saying I'd use javascript to either multiply meters by 1000 for kilometers or by 1609 for miles. There's even Javascript libraries to assist in this kind of internationalization.
Related
I have tremendous flows of point data (in 2D) (thousands every second). On this map I have several fixed polygons (dozens to a few hundreds of them).
I would like to determine in real time (the order of a few milliseconds on a rather powerful laptop) for each point in which polygons it lies (polygons can intersect).
I thought I'd use the ray casting algorithm.
Nevertheless, I need a way to preprocess the data, to avoid scanning every polygon.
I therefore consider using tree approaches (PM quadtree or Rtree ?). Is there any other relevant method ?
Is there a good PM Quadtree implementation you would recommend (in whatever language, preferably C(++), Java or Python) ?
I have developed a library of several multi-dimensional indexes in Java, it can be found here. It contains R*Tree, STR-Tree, 4 quadtrees (2 for points, 2 for rectangles) and a critbit tree (can be used for spatial data by interleaving the coordinates). I also developed the PH-Tree.
There are all rectange/point based trees, so you would have to convert your polygons into rectangles, for example by calculating the bounding box. For all returned bounding boxes you would have to calculate manually if the polygon really intersects with your point.
If your rectangles are not too elongated, this should still be efficient.
I usually find the PH-Tree the most efficient tree, it has fast building times and very fast query times if a point intersects with 100 rectangles or less (even better with 10 or less). STR/R*-trees are better with larger overlap sizes (1000+). The quadtrees are a bit unreliable, they have problems with numeric precision when inserting millions of elements.
Assuming a 3D tree with 1 million rectangles and on average one result per query, the PH-Tree requires about 3 microseconds per query on my desktop (i7 4xxx), i.e. 300 queries per millisecond.
I am currently working on remaking an old invoicing program that was originally written in VB6.
It has two parts, one on an android tablet, the other on a pc. The old database used , stored derived values because there was a chance that the calculations would be incorrect if repeated.
For example if one sold 5 items whose price was 10 euros at 10% discount and a tax value of 23% , it would store the above 4 values but also the result of the calucation of (5 * (10 * 1.23)) * 0.9.
I do not really like having duplicate or derivable information in my database, but the actual sell value must be the same, whether it is viewed on a tablet , or a pc.
So my question is , is there a chance (even the slightest one) that the above calucation (to a three decimal percision) would have different results on different operating systems (such as an android device and a desktop computer) ?
Thanks in advance for any help you can provide
Yes, it's possible. Floating-point arithmetic is always subject to rounding errors and different languages (and architectures) deal with those errors in different ways. There are best practices in dealing with these issues, though I don't consider myself knowledgeable enough to speak to them. But here are a couple of options for you.
Use a data type meant for floating-point arithmetic. For example, VB6 has a Single and Double type for floating point but also a Currency type for accurate decimal math.
Scale your floating-point values to integers and perform your calculations on these integer values. You can even store the results as integers in your DB. The ERP system we use does this and includes a data dictionary that defines how each type was scaled so that it can be "unscaled" before display.
Hope that helps.
Sliders are my app's primary user interaction element (go figure...). I use them to record percentage values which are then stored as Readings in my Core Data store. Based on the nature of percentage values, I would store them as decimal values between 0 and 1, and set the sliders to have a range from 0 to 1 and fire their value-changed actions continuously. When I need to display them I fetch them from the data store and display them as typical percentage values, e.g. 67%.
Now here's the catch: the value property of UISlider is of type float. That means I will run into rounding errors from the get-go. I'm nutty for accuracy, so I'm hoping to reduce the error margin as much as possible when I deal with them throughout my app.
What options are there for managing the percentage values which I'm reading off my sliders, storing in Core Data and displaying in the rest of my app? Or better yet, which of these options that I've come up with would be best for my app in terms of code maintainability, memory usage/performance and accuracy of the values obtained?
Use raw floats or doubles
Actually this is BAD, obviously because of rounding errors. Even 0.64 turns into 0.63 at some point in time (I've tested with my sliders and these come up a lot). With a difference potentially as large as 0.01, my app is definitely intolerant of this. Why am I even writing this as an option anyway?
Set slider range to between 0 and 100, read them, round up/down and store as integers
This is an interesting choice given that I'll only ever display the values as ##% and not 0.##. I won't need to perform arithmetic on these values either, so doing this looks alright:
// Recording and storing
// Slider range is 0 to 100
int percentage = (int) floor(slider.value); // Or ceil()
[reading setValue:[NSNumber numberWithInt:percentage]]; // Value is an integer
// Displaying
NSNumber *val = reading.value;
[readingLabel setText:[NSString stringWithFormat:#"%d%%", [val intValue]]];
This is not going to completely take away the rounding errors when I first read them off my sliders (they're still floats!), but floor() or ceil() should cut it, I think. I'm not entirely certain though; maybe someone here can provide more insight, which is the point of me asking this question.
Convert to, and store as, NSDecimalNumber objects
I've taken a look at the NSDecimalNumber class — percentages are base-10 factors after all — but given that it produces immutable objects, I'm not too sure I like the idea of writing long method calls all over my code repeatedly and creating a crapton of autoreleased objects everywhere.
Even creating NSDecimalNumbers out of primitives is a pain. Currently I can only think of doing this:
// Recording and storing
// Slider range is 0 to 1
NSDecimalNumber *decimalValue = [NSDecimalNumber decimalNumberWithString:
[NSString stringWithFormat:#"%0.2f",
slider.value]];
[reading setValue:decimalValue]; // Value is a decimal number
Multiplying them by 100 since I display them as ##% (like I said above) also gets really tedious and creates unnecessary extra objects which are then converted to NSStrings. I would go on, but I'd likely turn this post into a rant which is definitely not what I'm going for.
With that said, semantically NSDecimalNumber should make the most sense because, as I said above, I believe percentages are meant to be stored as decimal values between 0 and 1. However, looking at how my app works with percentage values, I don't know whether to choose multiplying them by 100 and storing as integers or working with NSDecimalNumber.
You can probably see that I'm already leaning slightly toward the second option (x100, use integers) because it's just more convenient and looks to be slightly better for performance. However, I'd like to see if anyone thinks the third is a better (more future proof?) one.
By the way, I don't mind modifying my data model to change the data type of the value attribute in my Reading entity, and modifying my existing code to accommodate the changes. I haven't done too much just yet because I've spent the rest of my time worrying about this.
Which of the above options do you think I should go for?
If all you need to do is read from a slider, save the values, and present them, dealing with primitive integers sourced from the scaled, rounded float slider input would be what I'd recommend. A slider isn't all that precise an input method, anyway, so your users won't notice if the rounding doesn't exactly match the pixel placement of the slider head.
I'd use the same sort of reasoning here as you do when determining the number of significant digits from a calculation that takes real-world data as its input (like a temperature reading, etc.). There's no sense in reporting a calculation to four significant digits if your input source only has a precision of two digits.
NSDecimals and NSDecimalNumbers are needed when you want to perform more extended calculations on decimal values, but want to avoid floating point errors. For example, I use them when running high-precision calculations in my application or if I need to manipulate currency in some way. Of the two, I stick with NSDecimal for performance reasons, using NSDecimalNumber on the occasions that I need to interact with Core Data or need to import numerical values into NSDecimal structs.
In this case, it seems like NSDecimal would be overkill, because you're not really adjusting the slider values in any way, just displaying them onscreen. If you did need to perform later manipulations (cutting in half, running through a formula, etc.), I'd recommend rounding the slider to an integer representation, creating an NSDecimal struct from that, performing calculations as NSDecimals, and then using the string output routines for NSDecimal / NSDecimalNumber to display the result onscreen. You can then easily save the calculated value as an NSDecimalNumber in Core Data or as a string representation in SQLite or another file.
Also, I wouldn't worry too much about performance on simple calculations like this until something like Instruments tells you they are a hotspot. Odds are, these calculations with NSDecimal, etc. won't be.
I have a map with about 80 annotations. I would like to do 3 things.
1) From my current location, I would like to know the actual route distance to that position. Not the linear distance.
2) I want to be able to show a list of all the annotations, but for every annotation (having lon/lat) I would like to know the actual route distance from my position to that position.
3) I would like to know the closest annotation to my possition using route distance. Not linear distance.
I think the answer to all these three points will be the same. But please keep in mind that I don't want to create a route, I just want to know the distance to the annotation.
I hope someone can help me.
Best regards,
Paul Peelen
From what I understand of your post, I believe you seek the Haversine formula. Luckily for you, there are a number of Objective-C implementations, though writing your own is trivial once the formula's in front of you.
I originally deleted this because I didn't notice that you didn't want linear distance at first, but I'm bringing it back in case you decide that an approximation is good enough at that particular point of the user interaction.
I think as pointed out before, your query would be extremely heavy for google maps API if you perform exactly what you are saying. Do you need all that information at once ? Maybe first it would be good enough to query just some of the distances based on some heuristic or in the user needs.
To obtain the distances, you could use a Google Maps GDirections object... as pointed out here ( at the bottom of the page there's "Routes and Steps" section, with an advanced example.
"The GDirections object also supports multi-point directions, which can be constructed using the GDirections.loadFromWaypoints() method. This method takes an array of textual input addresses or textual lat/lon points. Each separate waypoint is computed as a separate route and returned in a separate GRoute object, each of which contains a series of GStep objects."
Using the Google Maps API in the iPhone shouldn't be too difficult, and I think your question doesn't cover that, but if you need some basic example, you could look at this question, and scroll to the answer.
Good Luck!
Calculating route distance to about 80 locations is certain to be computationally intensive on Google's part and I can't imagine that you would be able to make those requests to the Google Maps API, were it possible to do so on a mobile device, without being severely limited by either the phone connection or rate limits on the server.
Unfortunately, calculating route distance rather than geometric distance is a very expensive computation involving a lot of data about the area - data you almost certainly don't have. This means, unfortunately, that this isn't something that Core Location or MapKit can help you with.
What problem are you trying to solve, exactly? There may be other heuristics other than route distance you can use to approximate some sort of distance ranking.
I am currently working on a map-based iPhone application and wish to display some information to the user. For my application, it makes sense to have a setting of some sort where the user can choose Miles or Kilometers. Is there a built in mechanism (maybe similar to string localization) for doing this kind of value switching so that I can avoid an if-block around each time I want to display something to the user?
Take a look at NSLocale. You should be able to get the current locale using [NSLocale currentLocale]. Then call [theLocale objectForKey: NSLocaleMeasurementSystem] and look at the results which should tell you if the users locale uses the metric system. The docs for NSLocale have a constants section which list all of the values that can be passed to the locale.
Using this you would make your own function that could be used in your program to return your distance in a locale specific way.
Based on my quick test NSLocaleUsesMetricSystem may not work for finding if the users' region uses kilometers or miles.
In the U.K, the distances are in Miles and speed in Miles per hour but NSLocaleUsesMetricSystem returns 1.
In the U.S, NSLocaleUsesMetricSystem returns 0 which is correct (distance is in Miles and speed in Miles per hour).
In India, NSLocaleUsesMetricSystemreturns 1 which is correct again (distance is in Kilometers and spee in kph).