如何比较复数十进制数和整数值

时间:2017-07-10 07:20:46

标签: ruby-on-rails ruby ruby-on-rails-5

我将获得所有靠近我的经度和经度的诊所。我用以下方法做到了。 dist的结果是一个很长的值,我需要将它与整数值进行比较。我不知道为什么我在比较dist和距离是一个整数值时得到这个错误。 这是我的错误:

NoMethodError (undefined method `<=' for (-2.693846638591123+0.0i):Complex):

这就是我为此所做的每一件事:

  def get_clinic_list
     ulat=params[:lat]
     ulang=params[:lang]
     distance=params[:distance]
     @clinic=[]
     Clinic.all.each do |clinic|
       if clinic_distance(ulat,ulang,distance,clinic.id)
         @doctor=DoctorProfile.find_by(user_id: clinic.user_id)
       end
     end
  end
  def clinic_distance(ulat, ulang,distance,clinic)
     @clinic=Clinic.find(clinic)
     diff_lat= ulat.to_f - @clinic.latitude.to_f
     diff_lang= ulang.to_f - @clinic.longitude.to_f
     #disc=Math.sqrt(((diff_lat*119.574)**2)+(diff_lang * Math.cos(diff_lat) * 111.320))
     a=(diff_lat * 119.574) ** 2
     b= diff_lang * Math.cos(diff_lat) * 111.320
     c=a+b
     logger.info "the c parameter is #{c}"

     dist=Math.sqrt(c)

     dist = dist ** 2
     if dist <= distance
         return true
     else
         return false
     end
  end

2 个答案:

答案 0 :(得分:2)

复数不支持<=>=(尽管它们支持==

最简单的解决方案是获得数字的绝对部分

if dist.abs <= distance

答案 1 :(得分:1)

clinic_distance方法的每一行都有一个错误。我尽力纠正它,但如果没有你的数据我就无法测试它。

问题不在于Complex个数字。我不知道这个Complex号码的来源,可能来自c中的否定Math.sqrt(c)

EarthRadius = 6371 # km
OneDegree = EarthRadius * 2 * Math::PI / 360 # 1° latitude in km

def get_clinic_list
  lat = params[:lat]
  lon = params[:lang] # :lang???
  max_distance = params[:distance] # :distance should probably be :max_distance
  @clinic = [] # What do you do with this empty array?
  Clinic.all.each do |clinic|
    if distance_in_km(lat, lon, clinic.latitude, clinic.longitude) < max_distance
      # Do you really want to keep overriding @doctor every time a clinic is found?
      @doctor = DoctorProfile.find_by(user_id: clinic.user_id)
    end
  end
  # You return every clinic, even ones far away...
end

def distance_in_km(lat1, lon1, lat2, lon2)
  diff_lat = lat1.to_f - lat2.to_f
  diff_lon = lon1.to_f - lon2.to_f

  lat_km = diff_lat * OneDegree
  lon_km = diff_lon * OneDegree * Math.cos(lat1.to_f * Math::PI / 180) # Math.cos expects a radian angle

  Math.sqrt(lat_km**2 + lon_km**2)
end