您正在这里运行模拟。首先为物理单位安装 SY gem:
gem install sy
然后,这就是如何绕过受控环境模拟:
require 'sy' # physical units
module ControlledEnvironment
class Air
SPECIFIC_HEAT_CAPACITY = 1.005.kJ.kg(-1).K(-1)
attr_accessor :volume, :temperature, :humidity, :pressure, :gas_composition
# to simplify things, let's forget about humidity, gas compositions...
def initialize( volume: 500.m(3),
temperature: SY::TRIPLE_POINT_OF_WATER + 20.K,
pressure: 101.3.kPa )
@volume, @temperature, @pressure = volume, temperature, pressure
end
def density
density_of_air_at_0_celsius = 1.205.kg.m(-3)
atmospheric_pressure = 101.3.kPa
density_of_air_at_0_celsius *
SY::TRIPLE_POINT_OF_WATER / temperature *
pressure / atmospheric_pressure
end
def heat!( energy )
@temperature += energy / ( SPECIFIC_HEAT_CAPACITY * volume * density )
end
def cool!( energy ); heat -energy end
end
class ThermalExchanger
attr_accessor :power_output
attr_reader :target
def initialize( power_output, target )
@power_output = power_output
@target = target
end
def act( delta_time, pow=power_output )
target.heat! pow * delta_time
end
end
class Heater < ThermalExchanger
def heat!( delta_time )
act delta_time
end
end
class Cooler < ThermalExchanger
def cool!( delta_time )
act( delta_time, -power_output )
end
end
end
设置了一个受控环境 mixin,让我们使用它创建一个 House 类。
class House
include ControlledEnvironment # including a mixin
# a house has air, one heater, and one cooler
attr_reader :heater, :cooler, :air
def initialize( heater_power: 1.kW, cooler_power: 1.kW,
air_volume: 500.m(3) )
@air = Air.new volume: air_volume
@heater = Heater.new( heater_power, @air )
@cooler = Cooler.new( cooler_power, @air )
end
# its temperature is defined as air temperature
def temperature
"#{(air.temperature - SY::TRIPLE_POINT_OF_WATER).to_f} centigrade"
end
# and, given current heating / cooling power settings, we can step forward in time
def step( delta_time=1.min )
heater.heat! delta_time
cooler.cool! delta_time
puts "After #{delta_time.in( :min )} minutes, the temperature is #{temperature}"
end
end
现在我们可以玩了:
house = House.new heater_power: 1.5.kW, cooler_power: 1.kW, air_volume: 1500.m(3)
house.temperature
#=> "20.0 centigrade"
house.step 1.h
#=> After 60 minutes, the temperature is 21.040302385090797 centigrade
house.step 1.h
#=> After 60 minutes, the temperature is 22.08429649473362 centigrade
house.heater.power_output = 0.kW # turn off the heater, for instance
#=> #<±Magnitude: 0.W >
house.step 30.min
#=> After 30 minutes, the temperature is 21.013285968306377 centigrade
100.times do house.step end