Jump to content

Resistance calculator: Difference between revisions

julia example
(julia example)
Line 264:
node.report("")
}</lang>
 
 
=={{header|Julia}}==
{{trans|Perl 6}}
<lang julia>using Formatting
import Base.*, Base.*
 
mutable struct Resistor
operator::Char
voltage::Float64
resistance::Float64
a::Union{Resistor, Nothing}
b::Union{Resistor, Nothing}
end
 
function res(r::Resistor)
if r != nothing
if r.operator == '+'
return res(r.a) + res(r.b)
elseif r.operator == '*'
return 1 / ((1 / res(r.a)) + (1 / res(r.b)))
end
end
return r.resistance
end
 
function setvoltage(r, voltage)
if r != nothing
if r.operator == '+'
ra = res(r.a)
rb = res(r.b)
setvoltage(r.a, voltage * ra / (ra + rb))
setvoltage(r.b, voltage * rb / (ra + rb))
elseif r.operator == '*'
setvoltage(r.a, voltage)
setvoltage(r.b, voltage)
end
r.voltage = voltage
end
end
current(r) = r.voltage / res(r)
 
effect(r) = r.voltage * current(r)
 
 
function report(r, level=1)
nfmt(x::Real) = rpad(format(x, precision=3), 12)
afmt(arr::Vector) = join(map(nfmt, arr), "| ")
println(afmt([res(r), r.voltage, current(r), effect(r)]), "| "^level, r.operator)
if r.a != nothing
report(r.a, level + 1)
end
if r.b != nothing
report(r.b, level+1)
end
end
 
Base.:+(a::Resistor, b::Resistor) = Resistor('+', 0.0, 0.0, a, b)
Base.:*(a::Resistor, b::Resistor) = Resistor('*', 0.0, 0.0, a, b)
(R1, R2, R3, R4, R5, R6, R7, R8, R9, R10) =
map(r -> Resistor('r', 0.0, r, nothing, nothing), [6, 8, 4, 8, 4, 6, 8, 10, 6, 2])
node = ((((R8 + R10) * R9 + R7) * R6 + R5) * R4 + R3) * R2 + R1
setvoltage(node, 18)
 
println(" Ohm Volt Ampere Watt Network tree")
report(node)
</lang>{{out}}
<pre>
Ohm Volt Ampere Watt Network tree
10.000 | 18.000 | 1.800 | 32.400 | +
4.000 | 7.200 | 1.800 | 12.960 | | *
8.000 | 7.200 | 0.900 | 6.480 | | | +
4.000 | 3.600 | 0.900 | 3.240 | | | | *
8.000 | 3.600 | 0.450 | 1.620 | | | | | +
4.000 | 1.800 | 0.450 | 0.810 | | | | | | *
12.000 | 1.800 | 0.150 | 0.270 | | | | | | | +
4.000 | 0.600 | 0.150 | 0.090 | | | | | | | | *
12.000 | 0.600 | 0.050 | 0.030 | | | | | | | | | +
10.000 | 0.500 | 0.050 | 0.025 | | | | | | | | | | r
2.000 | 0.100 | 0.050 | 0.005 | | | | | | | | | | r
6.000 | 0.600 | 0.100 | 0.060 | | | | | | | | | r
8.000 | 1.200 | 0.150 | 0.180 | | | | | | | | r
6.000 | 1.800 | 0.300 | 0.540 | | | | | | | r
4.000 | 1.800 | 0.450 | 0.810 | | | | | | r
8.000 | 3.600 | 0.450 | 1.620 | | | | | r
4.000 | 3.600 | 0.900 | 3.240 | | | | r
8.000 | 7.200 | 0.900 | 6.480 | | | r
6.000 | 10.800 | 1.800 | 19.440 | | r
</pre>
 
 
=={{header|Nim}}==
4,105

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.