Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAndrés Leal
9,563 PointsWhy Apple recommends using Double over Float?
Why Apple recommends using Double over Floats since we know that Double uses more memory than Floats? Why is that useful, and why Apple recommends using more space in memory, meaning using Doubles?
Thanks in advance to anyone who answers.
2 Answers
Michael Hulet
47,913 PointsBecause it has more space in memory, it can be more precise. Specifically, twice as precise (hence the name "Double
")
Computers only have a finite amount of space, so Float
s are called Float
s because in order to store a decimal number, a computer needs to do what's called "floating-point arithmetic". Basically it rounds the decimal number to the most precise place it can, so 22 / 7
might get rounded to 3.14285707
A Double
is basically 2 Float
s stored right next to each other in memory, so a Double
has twice the memory available as a Float
, which means it can be twice as accurate. So, where a Float
might be able to say that 22 / 7
is 3.14285707
, a Double
can say it's 3.1428571428571428
I know a Double
technically takes twice as much memory as a Float
, but that's not nearly as big of a deal as it sounds. Memory is actually extremely cheap nowadays. The newest iPhones have 4 GB of RAM, which means it has enough space to store 536,870,912 Double
s in memory at the same time before it has to start using swap space on its flash memory, which is orders of magnitude larger. It's likely much more important that your app be mathematically twice as precise than it be space-efficient, so Apple recommends that you always use Double
s
Andrés Leal
9,563 PointsThank you very much Michael for your detailed response.