Skip to content

Instantly share code, notes, and snippets.

@bdewater
Last active November 21, 2015 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bdewater/e3d735edd2533d4e7cea to your computer and use it in GitHub Desktop.
Save bdewater/e3d735edd2533d4e7cea to your computer and use it in GitHub Desktop.
Calculate screen pixel density
require 'bigdecimal'
# https://en.wikipedia.org/wiki/Pixel_density#Calculation_of_monitor_PPI
def calculate_ppi(height_pixels, width_pixels, diagonal_inches)
diagonal_pixels = Math.sqrt((height_pixels**2) + (width_pixels**2))
ppi = diagonal_pixels / diagonal_inches
end
def calculate_ppi_rounded(height_pixels, width_pixels, diagonal_inches)
ppi = calculate_ppi(height_pixels, width_pixels, diagonal_inches)
arg_digits = [height_pixels, width_pixels, diagonal_inches].collect(&:to_s).collect { |x| x.gsub(/\D/, '' )}.collect(&:length)
significant_digits = arg_digits.min
BigDecimal.new(ppi, significant_digits).to_i
end
# A Dell P2715Q monitor
puts calculate_ppi(3840, 2160, 27.0) # 163.17830889498507
puts calculate_ppi_rounded(3840, 2160, 27.0) # 163
# A MacBook Pro 13.3 with Retina display
puts calculate_ppi(2560, 1600, 13.3) # 226.98300468106115
puts calculate_ppi_rounded(2560, 1600, 13.3) # 227
# An iPhone 5 with Retina display
puts calculate_ppi(1136, 640, 4.0) # 325.9693237100694
puts calculate_ppi_rounded(1136, 640, 4.0) # 330 - only two significant digits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment