Created
          February 22, 2020 17:29 
        
      - 
      
- 
        Save kbob/bf5185546538b9205c5f4273d9f9db4c to your computer and use it in GitHub Desktop. 
    Numerically evaluate sine integral $ Si(x) $
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #!/usr/bin/env python3 | |
| from itertools import count | |
| # This is stable up to about x=34. | |
| # Above that, reimplement with rational arithmetic. | |
| def Si(x): | |
| """Sine integral. Numerically stable up to about x=34.""" | |
| sign = +1 | |
| fact = 1 | |
| numerator = x | |
| acc = 0 | |
| for n in count(): | |
| tnp1 = 2 * n + 1 | |
| if n: | |
| fact *= 2 * n * tnp1 | |
| abs_term = numerator / (tnp1 * fact) | |
| if acc - abs_term == acc: | |
| # further terms won't affect the result. | |
| break | |
| acc += sign * abs_term | |
| numerator *= x**2 | |
| sign = -sign | |
| return acc | |
| if __name__ == '__main__': | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| x = np.linspace(0, 15, 500) | |
| y = np.array([Si(xx) for xx in x]) | |
| plt.plot(x, y) | |
| plt.show() | |
      
      
  Author
  
  
        
      
            kbob
  
      
      
      commented 
        Feb 22, 2020 
      
    
  

  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment