ajuste linear de pontos

62 views
Skip to first unread message

Eduardo Boaventura

unread,
Oct 9, 2014, 10:02:51 AM10/9/14
to python...@googlegroups.com
Pessoal, tô meio perdido em conseguir fazer o programa abaixo funcionar. Alguém pode me ajudar?

# -*- coding: utf-8 -*-
'''Exercise 5.18: Fit a polynomial to experimental data
Suppose we have measured the oscillation period T of a simple pendulum
with a mass m at the end of a massless rod of length L. We have varied
L and recorded the corresponding T value. The measurements are found
in a file src/plot/pendulum.dat 10 . The first column in the file contains
L values and the second column has the corresponding T values.
a) Plot L versus T using circles for the data points.
b) We shall assume that L as a function of T is a polynomial. Use the
NumPy utilities polyfit and poly1d, as explained in Exercise 5.17, to fit
polynomials of degree 1, 2, and 3 to the L and T data. Visualize the poly-
nomial curves together with the experimental data. Which polynomial
fits the measured data best?
Filename: fit_pendulum_data.py.'''

from scitools.std import *

def readPenduloFile(sanity_check = True):
    infile = open('pendulum.dat', "r")
    Periodo = []
    cumprim = []
    for line in infile:
        line = line.split()
        Periodo.append(line[0]) # N.B. we're now filling out Periodo and cumprim lists
        cumprim.append(line[1])
    infile.close()

    Periodo = array(Periodo)
    cumprim = array(cumprim)

    x = Periodo
    y = cumprim
    deg = ([1,2,3])

    print type(x)
    print x


    t = zeros((3,3))   #Criate an 3x3 array
    yp= zeros((3,3))
    y_fitted = zeros((3,3))

    for xx in xrange(3):
        ll='deg='+str(deg[xx])       # text for curve label in legend
        t[xx]=x
        yp[xx]=y
        coeff = polyfit(t[xx], yp[xx], deg[xx])
        p = poly1d(coeff)
        print p                     # prints the polynomial expression
        y_fitted[xx]=p(t[xx])        # computes the polynomial at the x points
        plot(t[xx],y_fitted[xx], 'ro',label=ll)
        hold('True')                #evita que o segundo plot apague o primeiro e assim por diante

    # use red circles for data points and a blue line for the polynomial
    #plot(x, y, 'ro', x, y_fitted, 'b-')


    legend()
    title('Cumprimento x Periodo')
    xlabel("Periodo (C)")
    ylabel("Cumprimento (m)")
    savefig('pendulo.eps')
    show()

    return Periodo,cumprim

# run function
readPenduloFile()

Danimar Ribeiro

unread,
Oct 9, 2014, 10:46:24 AM10/9/14
to python...@googlegroups.com
É só fazer igualzinho ta ali no exemplo que vc vai conseguir.
No lugar de x e y usa suas variáveis T e L.

A função polyfit vai achar os coeficientes do polinômio de acordo com o grau que vc passar.
E dai a poly1d cria esse polinômio para você usar na função plot.


--
--
------------------------------------
Grupo Python-Brasil
http://www.python.org.br/wiki/AntesDePerguntar
 
<*> Para visitar o site do grupo na web, acesse:
http://groups.google.com/group/python-brasil
 
<*> Para sair deste grupo, envie um e-mail para:
python-brasi...@googlegroups.com

---
Você recebeu essa mensagem porque está inscrito no grupo "Python Brasil" dos Grupos do Google.
Para cancelar inscrição nesse grupo e parar de receber e-mails dele, envie um e-mail para python-brasi...@googlegroups.com.
Para mais opções, acesse https://groups.google.com/d/optout.



--
Danimar Ribeiro

Marcelo MD

unread,
Oct 9, 2014, 11:19:54 AM10/9/14
to python...@googlegroups.com
Senhores,

curve_fit do Scipy (http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.curve_fit.html) ou minimize do pacote lmfit (http://lmfit.github.io/lmfit-py/fitting.html) também resolvem a busca pelos coeficientes.

Provavelmente eles sejam só uma casca pras mesmas funções, lá embaixo =)

Abraço!
Marcelo Mallmann Dias

Danimar Ribeiro

unread,
Oct 9, 2014, 12:33:08 PM10/9/14
to python...@googlegroups.com
A questão pede para comparar 3 tipos de aproximação, com grau 1, 2 e 3,
então deve ser usado polyfit para poder controlar o grau do polinômio que se quer ajustar.
Reply all
Reply to author
Forward
0 new messages