Unfortunately, Swift doesn't have a decimal data type. Instead, it has Float and Double data types. Today we'll go over Floats and we'll give calculating WHIP another shot this time using Clayton Kershaw as our example.

What is a Float?
A Float is a data type like string and Int that accounts for decimals and fractions up to 14 places past the decimal point.
Why are Floats important?
As we saw when trying to calculate Cy Young's WHIP, Floats are important because they help us work with numbers that aren't integers or whole numbers, but rather numbers that are fractions or decimals.
When do we use Floats?
We typically assign Float data types to variables and constants we know will require short decimals. In baseball, this includes batting average, on-base percentage, slugging percentage, OPS, WHIP, ERA, innings pitched, and fielding percentage to name the biggies. Here are some examples:

Baseball stats rarely pass the decimal point by more than four places as seen above. This is perfect for Floats which are best for decimals of up to 14 places.
Another good reason to use Floats is to account for uncertain numerical outcomes. Classic cases of uncertain numerical outcomes occur when the output of a function is unknown going into the problem. For example, let's say Kershaw pitched a complete game (nine innings) giving up eight hits and one walk. This gives us a WHIP of 1 (8+1/9 = 1). We could have used the Int data type here because we had all whole numbers (9 innings, 8 hits, 1 walk, 1 WHIP).
But what are the chances over the course of an entire season or career that Kershaw's WHIP will always be an integer? He may throw a couple no-hitters (0 WHIP), have a bunch of solid one WHIP games, and maybe some bad 2 WHIP games, but chances are his WHIP will be a Float. Because this is a highly likely outcome it makes sense to assign the Float data type to associated variables and constants early on so they can account for these uncertainties later on.
So let's try calculating Kershaw's career WHIP (as of 6/19/16) using Floats:

Maybe you're thinking, wait, hits allowed and walks allowed will always be Ints! In the same way that strings and Ints don't play well together, neither do Ints and Floats.
There is a way to keep hits and walks allowed as Ints called type casting. We'll get to it down the road.
On Deck: Doubles
No comments:
Post a Comment