## Feature image:

I was recently updating one of the online workbooks for the RF Technology Certification program and decided to try and re-write one of the calculators using Python. The topic is teaching how to convert from dBm values to milliwatts without using a calculator, so the calculator does not just calculate the conversion, rather it tries to demonstrate the process of approximation in your head. In the end, I decided to keep the original Javascript calculator with some updates rather than replacing it with the Python version. Since I got pretty far in coding the Python version I thought I would share the code that I created here to hopefully provide some ideas for anyone trying to learn Python for use with RF problems. One of the nice aspects of Python is that it is quite fast and straightforward to create scripts, which is one of the reasons I got so far with the script below before deciding to go another route. You can copy and paste the code below into a Python interpreter and then call the getWatts() function (or try it out with the embedded Trinket player!).

import math def getWatts(dBmVal): dBm = dBmVal largePrefix = {0:"milliw",1: "W",2: "kilow",3: "megaw",4: "gigaw"} smallPrefix = {0:"milliwatts", 1: "microwatts",2: "nanowatts",3: "picowatts",4: "femtowatts"} ratio = (1,1.25,1.5, 2, 2.5, 3, 4, 5, 6, 8, 10) magnitude = math.trunc(dBm/10.0) quantity = ((dBm/10.0) - magnitude) * 10.0 prefixQuan = magnitude % 3 scaleSteps = math.trunc(magnitude/3.0) if magnitude >= 0: prefix = largePrefix[scaleSteps] resultVal = ratio[int(round(quantity))] milliResult = resultVal * (10**magnitude) prefixResult = (10**prefixQuan) * resultVal print "The order of magnitude is 10^{:d} milliwatts, of which there are {:.0f} dB quantity (about {:d} in ratio terms) ".format(magnitude, quantity, resultVal) print 'multiplying together we get {:,.0f} milliwatts.'.format(milliResult) if magnitude > 2: print "We can move up {:d} steps on the power scale".format(scaleSteps) print "Which is %d %satts" %(prefixResult, prefix) else: scaleSteps = math.fabs(scaleSteps) + 1 prefix = smallPrefix[scaleSteps] dBm = dBm + (scaleSteps * 30) magnitude = math.trunc(dBm/10) quantity = ((dBm/10.0) - magnitude) * 10.0 resultVal = ratio[int(round(quantity))] prefixQuan = magnitude prefixResult = (10**prefixQuan) * resultVal print "We can add {:d} multiples of 30dB to make the value positive {:d}".format(scaleSteps,dBm) print "Making the result in {} ({:d} steps down the power scale)".format(prefix,scaleSteps) print "From here we can say that there are {:.0f}dB or about {:d} times {:d}'s of {}".format(quantity,resultVal,10**prefixQuan,prefix) print "Which gives us %d %s" %(prefixResult, prefix)