Skip to content

Commit 2543c09

Browse files
authored
Support BigFloat#** for all Int::Primitive arguments (#13971)
1 parent 5bbb9c3 commit 2543c09

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

spec/std/big/big_float_spec.cr

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,9 @@ describe "BigFloat" do
186186
it { ("-0.05".to_big_f ** 10.to_big_i).should be_close("0.00000000000009765625".to_big_f, 1e-12) }
187187
it { ("0.1234567890".to_big_f ** 3.to_big_i).should be_close("0.001881676371789154860897069".to_big_f, 1e-12) }
188188

189+
it { ("10".to_big_f ** -5).should be_close("0.00001".to_big_f, 1e-12) }
190+
it { ("0.1".to_big_f ** -5).should be_close("100000".to_big_f, 1e-12) }
191+
189192
it { ("10".to_big_f ** (-5).to_big_i).should be_close("0.00001".to_big_f, 1e-12) }
190193
it { ("0.1".to_big_f ** (-5).to_big_i).should be_close("100000".to_big_f, 1e-12) }
191194
it { ("0".to_big_f ** 1.to_big_i).should eq(0.to_big_f) }

src/big/big_float.cr

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,18 @@ struct BigFloat < Float
171171
end
172172

173173
def **(other : Int) : BigFloat
174-
BigFloat.new { |mpf| LibGMP.mpf_pow_ui(mpf, self, other.to_u64) }
174+
# there is no BigFloat::Infinity
175+
if zero? && other < 0
176+
raise ArgumentError.new "Cannot raise 0 to a negative power"
177+
end
178+
179+
Int.primitive_ui_check(other) do |ui, neg_ui, big_i|
180+
{
181+
ui: BigFloat.new { |mpf| LibGMP.mpf_pow_ui(mpf, self, {{ ui }}) },
182+
neg_ui: BigFloat.new { |mpf| LibGMP.mpf_pow_ui(mpf, self, {{ neg_ui }}); LibGMP.mpf_ui_div(mpf, 1, mpf) },
183+
big_i: self ** {{ big_i }},
184+
}
185+
end
175186
end
176187

177188
def abs : BigFloat

0 commit comments

Comments
 (0)