컴퓨터 엑셀 워드 포토샵 구글어스 WINDOWS JAVASCRIPT JAVA C++

 
Sunday, December 24, 2006

Python/파이썬] 수학 함수 사용; math 모듈, sqrt() log() log10()


파이썬에서 수학 함수를 사용하기 위해서는, import math 로, 수학 함수 모듈을 로딩해 주어야 합니다. 아래 예제와 같습니다.

수학 함수 사용 예제
#!/usr/bin/python
# -*- coding: cp949 -*-

import math


# 제곱근 함수
print math.sqrt(2)
print math.sqrt(2.0)


# 자연 로그 함수
print math.log(12)
print math.log(12.0)


# 상용 로그 함수
print math.log10(12)
print math.log10(12.0)



인수를, 정수로 주든 실수로 주든, 결과는 같습니다.
D:\Z>0.py
1.41421356237
1.41421356237
2.48490664979
2.48490664979
1.07918124605
1.07918124605

D:\Z>



그리고 파이썬의 "대화 모드"에서도 import math 를 해주어야 합니다. 그렇지 않으면 NameError: name 'sqrt' is not defined (함수가 정의되어 있지 않다) 이런 에러가 납니다.
D:\Z>python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> print sqrt(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined
>>> print math.sqrt(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> import math
>>> print math.sqrt(2)
1.41421356237
>>>





tag: python
Python | 파이썬

0 Comments:

Post a Comment

<< Home RSS 2.0 feed

구글 Google 에서 제공하는 무료 블로그 서비스인 블로거 Blogger 의 인터넷 주소는 www.blogger.com 입니다. Blogger 에 블로그를 만들면, blogspot.com 이라는 주소에 블로그가 생성됩니다.
블로그를 직접 방문하지 않고도 최신 게시물을 구독하려면 RSS 2.0 feed 주소를 리더기에 등록하시면 됩니다.
Previous Posts
Monthly Archives
Top