Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from ply.lex import lex
- from ply.yacc import yacc
- from decimal import *
- setcontext(Context(prec=2000,rounding=ROUND_HALF_DOWN))
- factorial=[1]
- fac=Decimal('1')
- for i in range(2,1000):
- fac*=Decimal(i)
- factorial.append(fac)
- def sin(s):
- sin=Decimal(s)
- s=Decimal(s)
- for i in range(5,1000,4):
- sin+=(Decimal((s**Decimal(i)))/Decimal(factorial[i-1]))
- for i in range(3,1000,4):
- sin-=(Decimal((s**Decimal(i)))/Decimal(factorial[i-1]))
- return sin
- def cos(s):
- cos=Decimal('1')
- s=Decimal(s)
- for i in range(4,1000,4):
- cos+=(Decimal((s**Decimal(i)))/Decimal(factorial[i-1]))
- for i in range(2,1000,4):
- cos-=(Decimal((s**Decimal(i)))/Decimal(factorial[i-1]))
- return cos
- def tan(s):
- return sin(s)/cos(s)
- tokens=['NUM','PLUS','MINUS','TIMES','DIVIDE','LPAREN','RPAREN','SIN','COS','TAN']
- #tokens=['NUM','PLUS','MINUS','TIMES','DIVIDE','LPAREN','RPAREN', 'SIN']
- t_ignore=' \t\n'
- t_PLUS=r'\+'
- t_MINUS=r'\-'
- t_TIMES=r'\*'
- t_DIVIDE=r'/'
- t_LPAREN=r'\('
- t_RPAREN=r'\)'
- t_SIN=r'sin'
- t_COS=r'cos'
- t_TAN=r'tan'
- def t_NUM(t):
- r'\d+(\.\d+)?'
- t.value=Decimal(t.value)
- return t
- def t_SIN(t):
- r'sin\((\d+(\.\d+)?)\)'
- t.value=sin(Decimal(t))
- return t
- def t_COS(t):
- r'cos\((\d+(\.\d+)?)\)'
- t.value=cos(Decimal(t))
- return t
- def t_TAN(t):
- r'tan\((\d+(\.\d+)?)\)'
- t.value=tan(Decimal(t))
- return t
- def t_error(t):
- print('Bad Character: {!r}'.format(t.value[0]))
- t.lexer.skip(1)
- lexer=lex()
- def p_expr(p):
- '''
- expr : expr PLUS term
- | expr MINUS term
- '''
- if p[2]=='+':
- p[0]=p[1]+p[3]
- elif p[2]=='-':
- p[0]=p[1]-p[3]
- def p_expr_term(p):
- '''
- expr : term
- '''
- p[0]=p[1]
- def p_term(p):
- '''
- term : term TIMES factor
- | term DIVIDE factor
- '''
- if p[2]=='*':
- p[0]=p[1]*p[3]
- elif p[2]=='/':
- p[0]=p[1]/p[3]
- def p_term_factor(p):
- '''
- term : factor
- '''
- p[0]=p[1]
- def p_factor(p):
- '''
- factor : NUM
- '''
- p[0]=p[1]
- '''
- def p_factor(p):
- factor : SIN
- | COS
- | TAN
- if p[0]=='sin':
- p[0]=Decimal(sin(Decimal(p[1])))
- elif p[0]=='cos':
- p[0]=Decimal(cos(Decimal(p[1])))
- elif p[0]=='tan':
- p[0]=Decimal(sin(Decimal(p[1]))/cos(Decimal(p[1])))
- p[0]=p[1]
- '''
- def p_factor_group(p):
- '''
- factor : LPAREN expr RPAREN
- '''
- p[0]=p[2]
- def p_error(p):
- if p:
- print("Syntax error at '%s'" % p.value)
- else:
- print("Syntax error at EOF")
- #if __name__ == '__main__':
- parser=yacc()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement