[Tutor] Help with a Conversion
Peter Otten
__peter__ at web.de
Thu Jan 5 13:10:53 EST 2017
S. P. Molnar wrote:
> I have just started attempting programming in Python and am using Spyder
> with Python 3.5.2 on a Linux platform. (I first started programing in
> Fortran II using punched paper tape. Yes, am a rather elderly . . .).
>
> I have bumbled through, what I foolishly thought was a simple problem, a
> short program to change frequency to wavelength for a plot of
> ultraviolet spectra. I have attached a pdf of the program.
>
> During my attempt at programming I have printed results at various
> stages. Printing wavelength = [row[0] for row in data] gives me 25000
> as the first frequency in the wavelength list (the corresponding
> wavelength is 400).
>
> To change the frequency to wave length I did the following:
>
>
> p=1/1e7
> wave_length = p*np.array(frequency)
>
> (The relationship between wavelength and frequency is: wavelength =
> 1.0e7/frequency, where 1e7 is the speed of light)
>
>
> Apparently whhat I have managed to do is divide each element of the
> frequency list by 1/1e7.
>
> What I want to do is divide 1e7 by each element of the freqquency list.
>
> How di I do this?
Since you are using numpy anyway I'd put the frequencies into a numpy.array
as soon as possible:
>>> import numpy
>>> frequencies = numpy.array([25000, 1250, 400])
Because of numpy's "broadcasting" you can mix skalars and vectors as you
already tried -- and with the right formula, lamda = c / nu, you get the
correct result:
>>> speed_of_light = 1e7
>>> wavelengths = speed_of_light / frequencies
>>> wavelengths
array([ 400., 8000., 25000.])
The equivalent list comprehension in plain Python looks like this:
>>> frequencies = [25000, 1250, 400]
>>> wavelengths = [speed_of_light/freq for freq in frequencies]
>>> wavelengths
[400.0, 8000.0, 25000.0]
> Please keep in mind that many, many hyears ago I learned the ole
> arithmetic
That hasn't changed and is honoured by numpy; you were probably confused by
the new tool ;)
> and an not trying to start a flame war.
> Thanks in advance for the assistance tha I am sure will be most helpful.
More information about the Tutor
mailing list