Skip to content

tomstuart/dual_number

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

dual_number

This library provides a Ruby implementation of dual numbers, which are useful for forward mode automatic differentiation.

It is intended to accompany the article “Automatic differentiation in Ruby”.

That article explains the details, but here’s a brief demonstration:

$ irb -Ilib
>> require 'dual_number'
=> true

>> x = DualNumber(1, 2)
=> (1+2ε)

>> y = DualNumber(3, 4)
=> (3+4ε)

>> x + y
=> (4+6ε)

>> x * y
=> (3+10ε)

>> (x + 3) * 4
=> (16+8ε)

>> 3 + (4 * x)
=> (7+8ε)

One application of dual numbers is to use the second (“dual”) component to represent the derivative of the first (“real”) component. This lets us find the derivative of a function at a particular value by just passing in a dual number instead of a normal number:

>> def distance(time:)
     time * Math.sin(time * time) + 1
   end
=> :distance

>> value_and_derivative = distance(time: DualNumber(3, 1))
=> (2.2363554557252696-15.988226228682427ε)

>> value_and_derivative.real
=> 2.2363554557252696

>> value_and_derivative.dual
=> -15.988226228682427

If you have any questions, please get in touch via Twitter or email. If you find any bugs or other problems with the code, please open an issue.

About

A Ruby implementation of dual numbers.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages