728x90
728x170
다항식(Polynomial) 선형 리스트 표현과 계산 프로그램
다항식(Polynomial)
- 차 다항식
- : 다항식(Polynomial)
- : 계수(Coefficient)
- 의 : 지수(Exponent)
코드
방법 1
## 함수 선언 부분 def printPoly(p_x): term = len(p_x) - 1 # 최고차항 숫자 = 배열 길이 - 1 polyStr = "P(x) = " for i in range(len(px)): coef = p_x[i] # 계수 if (coef >= 0): polyStr += "+" polyStr += str(coef) + "x^" + str(term) + " " term -= 1 return polyStr def calcPoly(xVal, p_x): retValue = 0 term = len(p_x) - 1 # 최고사항 숫자 = 배열 길이 - 1 for i in range(len(px)): coef = p_x[i] # 계수 retValue += coef * xVal ** term term -= 1 return retValue ## 전역 변수 선언 부분 px = [7, -4, 0, 5] # =7x^3 - 4x^2 + 0x^1 + 5x^0 ## 메인 코드 부분 ## if __name__ == "__main__": pStr = printPoly(px) print(pStr) xValue = int(input("X 값--> ")) pxValue = calcPoly(xValue, px) print(pxValue)
결과 보기
P(x) = +7x^3 -4x^2 +0x^1 +5x^0 X 값--> 2 45 |
방법 2
- 지수가 상당히 큰 특수 다항식을 처리하기 위해 계수와 항의 차수를 리스트에 넣고 계산하는 방식
## 함수 선언 부분 def printPoly(t_x, p_x): polyStr = "P(x) = " for i in range(len(px)): term = t_x[i] # 항 차수 coef = p_x[i] # 계수 if (coef >= 0): polyStr += "+" polyStr += str(coef) + "x^" + str(term) + " " return polyStr def calcPoly(xVal, t_x, p_x): retValue = 0 for i in range(len(px)): term = t_x[i] # 항 차수 coef = p_x[i] # 계수 retValue += coef * xVal ** term term -= 1 return retValue ## 전역 변수 선언 부분 # 7x^300 -4x^20 +5x^0 tx = [300, 20, 0] px = [7, -4, 5] ## 메인 코드 부분 ## if __name__ == "__main__": pStr = printPoly(tx, px) print(pStr) xValue = int(input("X 값--> ")) pxValue = calcPoly(xValue, tx, px) print(pxValue)
결과 보기
P(x) = +7x^300 -4x^20 +5x^0 X 값--> 2 14259251834341402603879119818865647127360278755661553754452983145480669098343356943279587333 |
방법 3
- 2차원 배열을 활용하여 계산하는 방식
## 함수 선언 부분 ## def printPoly(p_x): polyStr = "P(x) = " for i in range(len(p_x[0])): term = p_x[0][i] # 항 차수 coef = p_x[1][i] # 계수 if (coef >= 0): polyStr += "+" polyStr += str(coef) + "x^" + str(term) + " " return polyStr def calcPoly(xVal, p_x): retValue = 0 for i in range(len(p_x[0])): term = p_x[0][i] # 항 차수 coef = p_x[1][i] # 계수 retValue += coef * xVal ** term term -= 1 return retValue ## 전역 변수 선언 부분 ## px = [[300, 20, 0], [7, -4, 5]] ## 메인 코드 부분 ## if __name__ == "__main__": pStr = printPoly(px) print(pStr) xValue = int(input("X 값--> ")) pxValue = calcPoly(xValue, px) print(pxValue)
결과 보기
P(x) = +7x^300 -4x^20 +5x^0 X 값--> 2 14259251834341402603879119818865647127360278755661553754452983145480669098343356943279587333 |
728x90
그리드형(광고전용)
'Source Code > Python' 카테고리의 다른 글
[Python] 10진수를 2진수/8진수/16진수로 변환하기 (0) | 2022.06.16 |
---|---|
[Python] 회문/팰린드롬(Palindrome) 판단하기 (0) | 2022.06.16 |
[Python] 괄호 매칭 검사 프로그램 (0) | 2022.05.30 |
[Python] 단순 연결 리스트(Singly Linked List) 프로그램 (0) | 2022.04.02 |
[Python] 선형 리스트(Linear List) 처리 프로그램 (0) | 2022.03.26 |
[Python] 파일 입출력 예제 (0) | 2021.08.07 |
[Python] matplotlib 라이브러리를 이용하여 그래프 그리기 (0) | 2020.03.24 |
[Python] BMI 계산기 (0) | 2019.05.02 |