Temperature conversion: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: Universal conversion.)
(+J)
Line 75: Line 75:
R 37.80
R 37.80
</pre>
</pre>

=={{header|J}}==
'''Solution''':<lang j> NB. Temp conversions are all linear polynomials
K2K =: 0 1 NB. K = (1 *k) + 0
K2C =: _273 1 NB. C = (1 *k) - 273
K2F =: _459.67 1.8 NB. F = (1.8*k) - 459.67
K2R =: 0 1.8 NB. R = (1.8*k) + 0

NB. Do all conversions at once (eval
NB. polynomials in parallel). This is the
NB. numeric matrix J programs would manipulate
NB. directly.
k2KCFR =: (k2K , k2C , k2F ,: k2R) p./ ]</lang>

'''Example''':<lang j> NB. Format matrix for printing
fmt =: '0.2' 8!:0 k2KCFR

NB. Tag each temp with scale, for human
NB. legibility.
kcfr =: 0 _1 |: 'KFCR' ,"0 1"_1 >@:fmt
kcfr 21
K 21.00
F-252.00
C-421.87
R 37.80

kcfr 0 NB. Absolute zero
K 0.00
F-273.00
C-459.67
R 0.00

kcfr 21 100 300 NB. List of temps works fine
K 21.00
F-252.00
C-421.87
R 37.80

K 100.00
F-173.00
C-279.67
R 180.00

K 300.00
F 27.00
C 80.33
R 540.00</lang>

'''Notes''': The approach is founded on polynomials, one for each conversion (e.g. <tt>Fahrenheit = 1.8*x - 459.67</tt> where <tt>x</tt> is measured in degrees Kelvin), and all polynomials are evaluated simultaneously using the built-in <tt>p.</tt>. Through some code decorations (specifically the <tt>/</tt> in <tt>p./</tt> the <tt>"0 1"_1</tt> and the <tt>0 _1 |:</tt>), the function is will convert arrays of temperatures of arbitrarily high dimension (a single temp, lists of temps, tables of temps, cubes of temps, etc).


=={{header|Python}}==
=={{header|Python}}==