Pose bone World Matrix rotation

I’m trying to align FK bones to their IK equivalents and have found code to copy the matrices of bones taking into account their parents, constraints, etc. The code works in most cases but parenting and inherited rotations can throw it off.
Here’s the code:

def quaternionRotation(armatureName, boneName):
    bone = bpy.data.armatures[armatureName].bones[boneName]
    bone_ml = bone.matrix_local
    bone_pose = bpy.data.objects[armatureName].pose.bones[boneName]
    bone_pose_m = bone_pose.matrix
    if bone.parent:
        parent = bone.parent
        parent_ml = parent.matrix_local
        parent_pose = bone_pose.parent
        parent_pose_m = parent_pose.matrix
        object_diff = parent_ml.inverted() * bone_ml
        pose_diff = parent_pose_m.inverted() * bone_pose_m
        local_diff = object_diff.inverted() * pose_diff
        local_diff = bone_ml.inverted() * bone_pose_m

Set the bone’s matrix_basis to the target bone’s matrix_basis multiplied it by the quaternion returned by the above function.

How can I build on this to be able to set a bone’s world rotation to match that of another bone?