romberg_integral 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 6460f69b68389239b30bb4f1db4e4fbb587a442d
4
+ data.tar.gz: 94d6e8eaf969e1289e19bb7e00aba21963d4aba3
5
+ SHA512:
6
+ metadata.gz: aeda9f7c1a400c6fa09c3f0045e7755a2ff00fa700aa3cab8ecfe36589b4b9014ad56d922c365da320783af36c9a486f43ef59c91c7842dc212d83e6aa109580
7
+ data.tar.gz: 5329114070e33eb555f79c5d8edac4471f6ccf7dc2d9f6e3097bce09df10bd77e4b0b7898158ff7594fbe1bac479ce5083f53eca24006299d53084d6118bee97
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.0
5
+ before_install: gem install bundler -v 1.15.4
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in romberg_integral.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Eric Boesch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # Romberg Integral
2
+
3
+ A pure Ruby implementation of Romberg numerical integration in one
4
+ variable.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'romberg_integral'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install romberg_integral
21
+
22
+ ## Usage
23
+
24
+ require "romberg_integral"
25
+
26
+ # Numerically integrate 1/x between 1 and 10
27
+ ri = RombergIntegral.new
28
+
29
+ # If you wish to change the error thresholds from their default values:
30
+ ri.max_call_cnt = 1025
31
+ ri.min_call_cnt = 9
32
+ ri.relative_error = 1e-9
33
+ ri.absolute_error = 1e-40
34
+
35
+ estimate = ri.integral(1, 10) { |x| 1.0/x }
36
+ actual = Math.log 10
37
+ error = (actual - estimate.value).abs
38
+ puts (estimate.aborted ? "Failed": "Success")
39
+ puts "True error = #{error} after #{estimate.call_cnt} calls."
40
+ puts estimate
41
+
42
+ ## Development
43
+
44
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
45
+
46
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
47
+
48
+ ## Contributing
49
+
50
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ericboesch/romberg_integral.
51
+
52
+ ## License
53
+
54
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList["test/**/*_test.rb"]
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "romberg_integral"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,178 @@
1
+ require "romberg_integral/version"
2
+
3
+ # Class to numerically estimate the integral of a function using
4
+ # Romberg integration, a faster relative of Simpson's method.
5
+ #
6
+ # == About the algorithm
7
+ #
8
+ # Romberg integration uses progressively higher-degree polynomial
9
+ # approximations each time you double the number of sample points. For
10
+ # example, it uses a 2nd-degree polynomial approximation (as Simpson's
11
+ # method does) after one split (<tt>2**1 + 1</tt> sample points), and
12
+ # it uses a 10th-degree polynomial approximation after five splits
13
+ # (<tt>2**5 + 1</tt> sample points). Typically, this will greatly
14
+ # improve accuracy (compared to simpler methods) for smooth functions,
15
+ # while not making much difference for badly behaved ones.
16
+ class RombergIntegral
17
+ # Acceptable absolute error.
18
+ #
19
+ # Each stage of Romberg integration nearly doubles the
20
+ # total number of function calls: specifically, the total calls made
21
+ # by the end of stage _n_ equals <tt>2**n+1</tt>. So, for example,
22
+ # the stage 1 estimate uses 3 function calls total, and stage 2
23
+ # adds 2 more function calls for a total of 5.
24
+ #
25
+ # The absolute error estimate after stage +n+ equals
26
+ #
27
+ # Math.abs(stage_n_estimate - stage_n_minus_1_estimate)
28
+ #
29
+ # If the total number of function calls made so far is greater than
30
+ # or equal to {#min_call_cnt} and the absolute error estimate is no
31
+ # greater than {#relative_error}, then {#integral} returns.
32
+ #
33
+ # Default value is 10**-20.
34
+ # @return [Numeric]
35
+ attr_accessor :absolute_error
36
+
37
+ # Acceptable relative error.
38
+ #
39
+ # The relative error is defined as
40
+ #
41
+ # absolute_error_estimate / integral_estimate
42
+ #
43
+ # If the total number of function calls made so far is greater than
44
+ # or equal to {#min_call_cnt} and the relative error estimate is no
45
+ # greater than this value, then {#integral} returns.
46
+ #
47
+ # Default value is 10**-10.
48
+ # @return [Numeric]
49
+ attr_accessor :relative_error
50
+
51
+ # Minimum number of function calls that {#integral} must make before
52
+ # returning due to having met the absolute or relative error
53
+ # threshold.
54
+ #
55
+ # Default value is 33.
56
+ # @return [Integer]
57
+ attr_accessor :min_call_cnt
58
+
59
+ # {#integral} must exit after calling the block this many times. This
60
+ # number is rounded up to the next value of the form <tt>2**n +
61
+ # 1</tt> which is also greater than or equal to {#min_call_cnt}. For
62
+ # example, a value of 50 is treated like <tt>65 = 2**6 + 1</tt>.
63
+ #
64
+ # Default value is 65537.
65
+ # @return [Integer]
66
+ attr_accessor :max_call_cnt
67
+
68
+ def initialize
69
+ @relative_error = 1e-10
70
+ @absolute_error = 1e-20
71
+ @max_call_cnt = 65537
72
+ @min_call_cnt = 33
73
+ end
74
+
75
+ # Estimate the integral between +x1+ and +x2+ of the block.
76
+ #
77
+ # @param x1 [Numeric] lower bound of integration. Must be finite.
78
+ # @param x2 [Numeric] upper bound of integration. Must be finite.
79
+ # @yield [x] +f(x)+, the function to be integrated.
80
+ #
81
+ # @return [RombergIntegral::Estimate]
82
+ def integral(x1, x2, &f)
83
+ x1, x2 = [x2, x1] if x1 > x2
84
+
85
+ # total is used to compute the trapezoid approximations. It is more or
86
+ # less a total of all f() values computed so far. The trapezoid
87
+ # method assigns half as much weight to f(x2) and f(x1) as it does to
88
+ # all other f() values, so f(x2) and f(x1) are divided by two here.
89
+ total = (yield(x1) + yield(x2))/2.0
90
+ call_cnt = 2
91
+ step_len = (x2 - x1).to_f
92
+
93
+ estimate = total * step_len # 0th trapezoid approximation.
94
+ row = [estimate]
95
+ split = 1
96
+ steps = 2
97
+ aborted = false
98
+ abs_error = nil
99
+
100
+ loop do
101
+ # Don't let step_len drop below the limits of numeric precision.
102
+ # (This should prevent infinite loops, but not loss of accuracy.)
103
+ if x1 + step_len/steps == x1 || x2 - step_len/steps == x2
104
+ aborted = true
105
+ break
106
+ end
107
+
108
+ # Compute the (split)th trapezoid approximation.
109
+ x = x1 + step_len/2
110
+ while x < x2
111
+ total += yield(x)
112
+ call_cnt += 1
113
+ x += step_len
114
+ end
115
+ row.unshift total * step_len / 2
116
+
117
+ # Compute the more refined approximations, based on the (split)th
118
+ # trapezoid approximation and the various (split-1)th refined
119
+ # approximations stored in @row.
120
+ pow4 = 4.0
121
+ 1.upto(split) do |td|
122
+ row[td] = row[td-1] + (row[td-1]-row[td])/(pow4 - 1)
123
+ pow4 *= 4
124
+ end
125
+
126
+ # row[0] now contains the (split)th trapezoid approximation,
127
+ # row[1] now contains the (split)th Simpson approximation, and
128
+ # so on up to row[split] which contains the (split)th Romberg
129
+ # approximation.
130
+
131
+ # Is this estimate accurate enough?
132
+ old_estimate = estimate
133
+ estimate = row[-1]
134
+ abs_error = (estimate - old_estimate).abs
135
+ if call_cnt >= min_call_cnt
136
+ break if abs_error <= absolute_error ||
137
+ abs_error <= relative_error * estimate.abs
138
+ if call_cnt >= max_call_cnt
139
+ aborted = true
140
+ break
141
+ end
142
+ end
143
+ split += 1
144
+ step_len /=2
145
+ steps *= 2
146
+ end
147
+
148
+ Estimate.new(estimate, aborted, call_cnt, abs_error)
149
+ end
150
+
151
+ # Structure to hold information returned by {RombergIntegral#integral}
152
+ #
153
+ # @attr [Boolean] aborted True if call exited before reaching either
154
+ # the relative or absolute error thresholds. This could be
155
+ # because {RombergIntegral#max_call_cnt} was reached or because
156
+ # loss of precision was detected.
157
+ #
158
+ # @attr [Integer] call_cnt Number of function calls made during the
159
+ # estimation process.
160
+ # @attr [Float] value The estimated value
161
+ # @attr [Float] absolute_error Estimated limit on the error in {#value}
162
+ Estimate = Struct.new(:value, :aborted, :call_cnt, :absolute_error) do
163
+ # @return [Float, nil] Absolute error estimate divided by
164
+ # estimate, or nil if estimate is zero.
165
+ def relative_error
166
+ value.zero? ? nil : (absolute_error / value).abs
167
+ end
168
+
169
+ def to_f
170
+ value
171
+ end
172
+
173
+ def to_s
174
+ "Estimate[#{value} +/- #{absolute_error}, call_cnt=#{call_cnt}, " \
175
+ "aborted=#{aborted}]"
176
+ end
177
+ end
178
+ end
@@ -0,0 +1,3 @@
1
+ class RombergIntegral
2
+ VERSION = "0.1.1"
3
+ end
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "romberg_integral/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "romberg_integral"
8
+ spec.version = RombergIntegral::VERSION
9
+ spec.authors = ["Eric Boesch"]
10
+ spec.email = ["ericboesch@gmail.com"]
11
+
12
+ spec.summary = %q{Romberg numerical integration class.}
13
+ spec.homepage = "https://github.com/ericboesch/romberg_integral"
14
+ spec.license = "MIT"
15
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
16
+ f.match(%r{^(test|spec|features)/})
17
+ end
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_development_dependency "bundler", "~> 1.15"
23
+ spec.add_development_dependency "rake", "~> 10.0"
24
+ spec.add_development_dependency "minitest", "~> 5.0"
25
+ end
metadata ADDED
@@ -0,0 +1,97 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: romberg_integral
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Eric Boesch
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-10-31 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.15'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.15'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ description:
56
+ email:
57
+ - ericboesch@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".travis.yml"
64
+ - Gemfile
65
+ - LICENSE.txt
66
+ - README.md
67
+ - Rakefile
68
+ - bin/console
69
+ - bin/setup
70
+ - lib/romberg_integral.rb
71
+ - lib/romberg_integral/version.rb
72
+ - romberg_integral.gemspec
73
+ homepage: https://github.com/ericboesch/romberg_integral
74
+ licenses:
75
+ - MIT
76
+ metadata: {}
77
+ post_install_message:
78
+ rdoc_options: []
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ required_rubygems_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ requirements: []
92
+ rubyforge_project:
93
+ rubygems_version: 2.5.1
94
+ signing_key:
95
+ specification_version: 4
96
+ summary: Romberg numerical integration class.
97
+ test_files: []