I am writing a program to calculate wages (usually...
# mathematics
s
I am writing a program to calculate wages (usually doubles are a no-no, but I think it is ok in this case). Part of the company’s requirements are that the new salary must be expressed in terms of the old rate with a proportionate number of hours added to the total hours worked. This function is not giving me the answers that a colleague drafted on paper - are our equations correct?
Copy code
/**
Given:
old rate = $30/hour
new rate = $37.5/hour
Hours in new rate = 36.72
Total hours = 52.21

Equations:
1/x := 30/37.5 == 37.5/30 = x; x=1.25, so 1 hour of the new rate is worth 1.25 hours in the old rate.

Hours in old rate = total hours - hours in new rate = 52.21 - 32.67 = 15.49
(1.25 * hours worked in new rate) * old rate = equivalent hours in new rate * old rate = salary for hours in new rate

Calculations:
1.25   * 36.72   = 45.9 upscaled hours
45.9   * 30      = $1,377  for hours in new rate
15.49  * 30      = $464.70 for hours in old rate
$1,377 + $464.70 = $1,841.70 total
Check: 
36.72  * $37.5   = $1,377  for hours in new rate
15.49  * $30     = $464.70 for hours in old rate
$1,377 + $464.70 = $1,841.70 total
 * */
Copy code
fun calculateHoursInNewRate(oldRatePerHour: Double,newRatePerHour: Double,totalHoursWorked: Double,hoursInNewRateWorked: Double): Double {
    val equivalentOfOldHoursWorkedInNewRate = newRatePerHour / oldRatePerHour
    val hoursInOldRate = totalHoursWorked - hoursInNewRateWorked
    val upscaledHours = equivalentOfOldHoursWorkedInNewRate * hoursInNewRateWorked
    val salaryForHoursInNewRateWorked = upscaledHours * oldRatePerHour
    val salaryForHoursInOldRateWorked = hoursInOldRate * oldRatePerHour
    return salaryForHoursInNewRateWorked + salaryForHoursInOldRateWorked
}
g
Hi! I did not delve into the essence of the formulas. But I tested your function and it works well: https://pl.kotl.in/X0O9ImTEt The only thing that looks odd is that you have different orders of input variables in your message and in your function. Your message mentions order "old rate, new rate, hours in new rate, total hours" and your function uses order "old rate, new rate, total hours, hours in new rate".
s
So you think the answers it outputs are correct?
a
For monetary calculations, if exact answers are required, you should not use Double. See item 60, https://www.oreilly.com/library/view/effective-java-3rd/9780134686097/
plus1 1